SnowFlake 全局唯一 id 服务

项目是采用 dubbo + spring boot 2.1.1.RELEASE ,首先来看我们的依赖

注意:这里的 common 就是我们项目中的自定义 通用 common jar 包,用来放一些通用的类、接口、常量 等等

        <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
        <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-test</artifactId>
           <scope>test</scope>
        </dependency>
        <dependency>
          <groupId>com.hmily.dubbo</groupId>
          <artifactId>common</artifactId>
          <version>0.0.1-SNAPSHOT</version>
        </dependency>

看看 application.properties 的配置

server.port=8020
server.servlet.context-path=/
# snowFlake 的配置
##  server setting for LongID Gene  
snowFlake.workerId = 0
snowFlake.datacenterId = 0
# dubbo 的配置
# Dubbo Config properties
dubbo.application.id=rabbitmq-snowFlake
dubbo.application.name=rabbitmq-snowFlake
dubbo.application.qosPort=22212
dubbo.application.qosEnable=true
dubbo.scan.basePackages=com.hmily.dubbo.snowFlakeDemo.*
dubbo.protocol.id=dubbo
dubbo.protocol.name=dubbo
dubbo.protocol.port=12343
dubbo.registry.id=rabbitmq-snowFlake-registry
dubbo.registry.address=zookeeper://130.80.151.179:2181
# Enables Dubbo All Endpoints
management.endpoint.dubbo.enabled = true
management.endpoint.dubbo-shutdown.enabled = true
management.endpoint.dubbo-configs.enabled = true
management.endpoint.dubbo-services.enabled = true
management.endpoint.dubbo-references.enabled = true
management.endpoint.dubbo-properties.enabled = true
# Dubbo Health
## StatusChecker Name defaults (default : "memory", "load" )
management.health.dubbo.status.defaults = memory
## StatusChecker Name extras (default : empty )
management.health.dubbo.status.extras = load,threadpool

接着就是我们核心 SnowFlake 实现

public class SnowFlake {
      
    protected static final Logger LOG = LoggerFactory.getLogger(SnowFlake.class);
    
    @Value("snowFlake.workerId")
    private static long workerId;
    @Value("snowFlake.datacenterId")
    private static long datacenterId;
    
    static SnowFlake instance = new SnowFlake(workerId, datacenterId);
    
    private long sequence = 0L;
 
    private long twepoch = 1288834974657L;
    // 机器标识位数 
    private long workerIdBits = 5L;
 // 数据中心标识位数
    private long datacenterIdBits = 5L;
 // 机器ID最大值 
    private long maxWorkerId = -1L ^ (-1L << workerIdBits);
 // 数据中心ID最大值 
    private long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
 // 毫秒内自增位 
    private long sequenceBits = 12L;
 // 机器ID偏左移12位 
    private long workerIdShift = sequenceBits;
 // 数据中心ID左移17位 
    private long datacenterIdShift = sequenceBits + workerIdBits;
 // 时间毫秒左移22位
    private long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
    private long sequenceMask = -1L ^ (-1L << sequenceBits);
 
    private long lastTimestamp = -1L;
 
    public SnowFlake(long workerId, long datacenterId) {
        // sanity check for workerId
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
        }
        if (datacenterId > maxDatacenterId || datacenterId < 0) {
            throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
        }
        this.workerId = workerId;
        this.datacenterId = datacenterId;
        //LOG.info(String.format("worker starting. timestamp left shift %d, datacenter id bits %d, worker id bits %d, sequence bits %d, workerid %d", timestampLeftShift, datacenterIdBits, workerIdBits, sequenceBits, workerId));
    }
 
    public synchronized long nextId() {
        long timestamp = timeGen();
 
        if (timestamp < lastTimestamp) {
            LOG.error(String.format("clock is moving backwards.  Rejecting requests until %d.", lastTimestamp));
            throw new RuntimeException(String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }
 
        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }
 
        lastTimestamp = timestamp;
 
        return ((timestamp - twepoch) << timestampLeftShift) | (datacenterId << datacenterIdShift) | (workerId << workerIdShift) | sequence;
    }
 
    protected long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }
 
    protected long timeGen() {
        return System.currentTimeMillis();
    }
    
    public static long getId() {
       return instance.nextId();
    }
}

接着封装一下我们的 Service 方法

public interface ISnowFlakeService {

   long getSnowFlakeID();
   
   long[] getSnowFlakeIDs(int size);
}

写一个 service 的实现类

@Service
public class SnowFlakeServiceImpl implements ISnowFlakeService {

    private final  static Logger log = LoggerFactory.getLogger(SnowFlakeServiceImpl.class);

   @Override
   public long getSnowFlakeID() {
        long id = SnowFlake.getId();
        log.info("id: {}", id);
        return id;
   }

   @Override
   public long[] getSnowFlakeIDs(int size) {
      if (size < 1) {
         throw new SnowFlakeCustomException(500, " size is illegal");
      }
      long[] ids = new long[size];
      for (int i = 0; i < size; i++) {
            long id = SnowFlake.getId();
         ids[i] = id;
            log.info("id: {}", id);
      }
      return ids;
   }

}

写个 Controller 测试一下是否能生成 id

@RestController
public class TestController {
   
   private static final Logger log = LoggerFactory.getLogger(TestController.class);

   @GetMapping("/test")
   public String test() {
      return "hello";
   }
   
   @GetMapping("/test/longid")
   public String testId() {
      String res = null;
      for(int i = 0; i < 5; i++) {
         Long id = SnowFlake.getId();
         log.info("id: {}", id);
         if (i == 0) {
            res = id.toString();
         }
      }
      return res;
   }
}

测试 test/longid 接口,看看是否能正常获取 id。能获取 id 就到了提供 dubbo RPC 服务。
首先,我们是有一个 通用 common 的 jar 包,里面定义了一些对外的 RPC 接口规范,例如这里就定义了 ISnowFlakeServiceApi 接口,这样就能管理好服务方的入参类型 和 返回值类型。

public interface ISnowFlakeServiceApi {

    long getSnowFlakeID();

    long[] getSnowFlakeIDs(int size);

}

然后我们在 snowFlakeDemo ,雪花算法实现的 demo 里面,对外提供服务时要实现这个接口

@Service(
        version = "1.0.0",
        application = "${dubbo.application.id}",
        protocol = "${dubbo.protocol.id}",
        registry = "${dubbo.registry.id}"
)
public class SnowFlakeProvider implements ISnowFlakeServiceApi {

    @Autowired
    private ISnowFlakeService snowFlakeService;

    @Override
    public long getSnowFlakeID(){
        return snowFlakeService.getSnowFlakeID();
    }

    @Override
    public long[] getSnowFlakeIDs(int size){
        return snowFlakeService.getSnowFlakeIDs(size);
    }
}

注意: 这里的 @Service 注解使用 import com.alibaba.dubbo.config.annotation.Service;

我们的调用方 rabbitmq-common 项目里面,也是要依赖 common 的

<dependency>
    <groupId>com.hmily.dubbo</groupId>
    <artifactId>common</artifactId>
    <version>0.0.1-SNAPSHOT</version>
</dependency>

看看 application.properties 的配置

server.port=8030
server.servlet.context-path=/

spring.http.encoding.charset=UTF-8
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
spring.jackson.default-property-inclusion=NON_NULL

# Dubbo Config properties
dubbo.application.id=rabbitmq-common
dubbo.application.name=rabbitmq-common
dubbo.application.qosPort=22212
dubbo.application.qosEnable=true
dubbo.scan.basePackages=com.hmily.rabbitmq.rabbitmqcommon.*
dubbo.protocol.id=dubbo
dubbo.protocol.name=dubbo
dubbo.protocol.port=12343
dubbo.registry.id=rabbitmq-common-registry
dubbo.registry.address=zookeeper://130.80.151.179:2181

# Enables Dubbo All Endpoints
management.endpoint.dubbo.enabled = true
management.endpoint.dubbo-shutdown.enabled = true
management.endpoint.dubbo-configs.enabled = true
management.endpoint.dubbo-services.enabled = true
management.endpoint.dubbo-references.enabled = true
management.endpoint.dubbo-properties.enabled = true

# Dubbo Health
## StatusChecker Name defaults (default : "memory", "load" )
management.health.dubbo.status.defaults = memory
## StatusChecker Name extras (default : empty )
management.health.dubbo.status.extras = load,threadpool

写一个测试接口,看看能否调用 RPC 接口成功

@RestController
public class TestController {
   
   private static final Logger log = LoggerFactory.getLogger(TestController.class);

    @Reference(version = "${snowFlakeServiceApi.version}",
            application = "${dubbo.application.id}",
            interfaceName = "com.hmily.dubbo.common.service.ISnowFlakeServiceApi",
            check = false,
            timeout = 1000,
            retries = 0
    )
    private ISnowFlakeServiceApi snowFlakeServiceApi;


    @GetMapping("/test/longid/rpc")
    public String testIdByRPC() {
        Long id = snowFlakeServiceApi.getSnowFlakeID();
        log.info("id: {}", id);
        return id.toString();

    }
}

就这样,SnowFlake 全局唯一 id 生成服务 完成了。

完整代码:
https://github.com/hmilyos/common.git 

https://github.com/hmilyos/snowFlakeDemo.git

https://github.com/hmilyos/rabbitmq-common.git       available 分支
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,013评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,205评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 152,370评论 0 342
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,168评论 1 278
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,153评论 5 371
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,954评论 1 283
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,271评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,916评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,382评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,877评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,989评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,624评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,209评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,199评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,418评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,401评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,700评论 2 345

推荐阅读更多精彩内容