public final class Snowflake extends Object implements IdGenerator
基于snowflake算法的ID生成器 BINARY(Long.MAX_VALUE )=0111111111111111111111111111111111111111111111111111111111111111 BINARY(2039-09-07 23:47:35.551)=0000000000000000000000011111111111111111111111111111111111111111 0 | 0000000000 0000000000 0000000000 0000000000 0 | 00000 | 00000 | 0000000000 00 - | ------------------timestamp------------------ | -did- | -wid- | -----seq----- 00 ~ 00:1位未使用(实际上也是作为long的符号位) 01 ~ 41:41位为毫秒级时间(能到“2039-09-07 23:47:35.551”,41位bit的最大Long值,超过会溢出) 42 ~ 46:5位datacenterId 47 ~ 51:5位workerId(并不算标识符,实际是为线程标识), 52 ~ 63:12位该毫秒内的当前毫秒内的计数 毫秒内序列 (由datacenter和机器ID作区分),并且效率较高。经测试, snowflake每秒能够产生26万ID左右,完全满足需要。 计算掩码的三种方式: a:(1 << bits) - 1 b:-1L ^ (-1L << bits) c:Long.MAX_VALUE >>> (63 - bits)
| 构造器和说明 |
|---|
Snowflake() |
Snowflake(int workerId)
no datacenterId
max sequence count: 16384
max work count : 32
max time at : 2527-06-23 14:20:44.415
|
Snowflake(int workerId,
int datacenterId)
sequenceBits: 12 bit, value range of 0 ~ 4095(111111111111)
workerIdBits: 5 bit, value range of 0 ~ 31(11111)
datacenterIdBits: 5 bit, value range of 0 ~ 31(11111)
workerIdShift: sequenceBits,左移12位(seq12位)
datacenterIdShift: sequenceBits+workerIdBits,即左移17位(wid5位+seq12位)
timestampShift: sequenceBits+workerIdBits+datacenterIdBits,
即左移22位(did5位+wid5位+seq12位)
timestampMask: (1L<<(MAX_SIZE-timestampShift))-1 = (1L<<41)-1
|
Snowflake(int workerId,
int datacenterId,
int sequenceBits,
int workerIdBits,
int datacenterIdBits) |
public Snowflake(int workerId,
int datacenterId,
int sequenceBits,
int workerIdBits,
int datacenterIdBits)
public Snowflake(int workerId,
int datacenterId)
workerId - datacenterId - public Snowflake()
public Snowflake(int workerId)
workerId - public long generateId()
IdGeneratorgenerateId 在接口中 IdGeneratorpublic long nextId()
Copyright © 2023. All rights reserved.