Documentation

A good document is like an intriguing story.

Usage

通过local、redis 和 zookeeper 生成全局ID。

                        Copy
                        
<dependency>
    <groupId>net.dragonshard</groupId>
    <artifactId>dragonshard-id-generator-starter</artifactId>
    <version>${latest.version}</version>
</dependency>
                        
                    

配置文件

                        Copy
                        
id-generator:
    local:
        enabled: true
        data-center: 2
        machine: 2
    redis:
        enabled: false
        prefix: idg
    zookeeper:
        enabled: false
                        
                    

配置项前缀dragonshard.id-generator

配置项 默认值 选项 描述
local.enabled true true / false 是否开启
local.data-center 1L Long 数据中心标识
local.machine 1L Long 机器标识
redis.enabled true true / false 是否开启
redis.prefix DsfIdGenerator String 前缀
redis.length 8 Integer 长度最大为8位,如果 > 8,则取8
zookeeper.enabled true true / false 是否开启

LocalIdGenerator

使用 SnowFlake 算法生成64位ID,具体实现细节不再复述,网上很多。

                        Copy
                        
// 根据 数据中心标识 和 机器标识 生成ID
String nextUniqueId(long dataCenterId, long machineId) throws Exception;
// 根据默认配置生成ID
String nextUniqueId() throws Exception;
// 根据 数据中心标识 和 机器标识 生成 count 个ID
String[] nextUniqueIds(long dataCenterId, long machineId, int count) throws Exception;
// 根据默认配置生成 count 个ID
String[] nextUniqueIds(int count) throws Exception;


// 在代码中使用
@Autowired
private LocalIdGenerator localIdGenerator;

String id = localIdGenerator.nextUniqueId();
                        
                    

RedisIdGenerator

在Redis上分布式生成全局唯一ID,Key名为 prefix + ":" + name + ":" + key

ID值的前半部分为 yyyyMMddHHmmssSSS 格式的17位数字,后半部分由配置文件中的 redis.length 决定( 长度最大为8位,如果 > 8,则取8 ), 如果小于 length 的数位用0补足。

                        Copy
                        
// 在代码中使用
@Autowired
private RedisIdGenerator redisIdGenerator;

// 实际生成key = prefix:name:key,value= 2019081711223366600000001
String id1 = redisIdGenerator.nextUniqueId("name", "key", 1, 8);
// 实际生成key = prefix:name:key,value= 2019081711223366645
String id2 = redisIdGenerator.nextUniqueId("name", "key", 12345, 2);
                        
                    

在 dragonshard-sample 中提供了对应的测试用例, 在源码中查看

ZookeeperIdGenerator

待完善……