public class SnowFlake { //开始时间戳 private final static long START_STMP = 1480166465631L; //机房占用的位数 private final static long DATACENTER_BIT = 5; //机器占用的位数 private final static long MACHINE_BIT = 5; //序列号占用的位数 private final static long SEQUENCE_BIT = 12; //机房部分的最大值 private final static long MAX_DATACENTER_NUM = ~(-1L << DATACENTER_BIT); //2的5次幂减1 = 31 //机器部分的最大值 private final static long MAX_MACHINE_NUM = ~(-1L << MACHINE_BIT); //序列号部分的最大值 private final static long MAX_SEQUENCE_NUM = ~(-1L << SEQUENCE_BIT); //机器部分的向左位移 private final static long MACHINE_LEFT = SEQUENCE_BIT; //机房部分的向左位移 private final static long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT; //时间戳部分的向左位移 private final static long TIMESTMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT; private long dataCenterId; //机房标识 private long machineId; //机器标识 private long sequence = 0L; private long lastStmp = -1L; //上一次的时间戳 public SnowFlake(long dataCenterId, long machineId) { if (dataCenterId > MAX_DATACENTER_NUM || dataCenterId < 0) { throw new IllegalArgumentException("dataCenterId can't be greater than MAX_DATACENTER_NUM or less than 0"); } if (machineId > MAX_MACHINE_NUM || machineId < 0) { throw new IllegalArgumentException("machineId can't be greater than MAX_MACHINE_NUM or less than 0"); } this.dataCenterId = dataCenterId; this.machineId = machineId; } public synchronized long nextId() { long nowStmp = System.currentTimeMillis(); if (nowStmp < lastStmp) { throw new RuntimeException("Clock moved backwards. Refusing to generate id"); } if (nowStmp == lastStmp) { //if条件里表示当前调用和上一次调用落在了相同毫秒内,只能通过第三部分,序列号自增来判断为唯一,所以+1. sequence = (sequence + 1) & MAX_SEQUENCE_NUM; //通过位与运算保证计算的结果范围始终是 0 - MAX_SEQUENCE_NUM //同一毫秒的序列数已经达到最大,只能等待下一个毫秒 if (sequence == 0L) { nowStmp = getNextMill(); } } else { //不同毫秒内,序列号置为0 //执行到这个分支的前提是nowStmp > lastStmp,说明本次调用跟上次调用对比,已经不再同一个毫秒内了,这个时候序号可以重新回置0了。 sequence = 0L; } lastStmp = nowStmp; /** * return ((timestamp - 1288834974657) << 22) | datacenterId << 17) | (workerId << 12) | sequence; */ //左移运算是为了将数值移动到对应的段(41、5、5,12那段因为本来就在最右,因此不用左移)。 //然后对每个左移后的值(la、lb、lc、sequence)做位或运算,是为了把各个短的数据合并起来,合并成一个二进制数。 //最后转换成10进制,就是最终生成的id return (nowStmp - START_STMP) << TIMESTMP_LEFT | dataCenterId << DATACENTER_LEFT | machineId << MACHINE_LEFT | sequence ; } private long getNextMill() { long nextMill = System.currentTimeMillis(); while (nextMill <= lastStmp) { nextMill = System.currentTimeMillis(); } return nextMill; } public static void main(String[] args) { SnowFlake snowFlake = new SnowFlake(17,25); for (int i = 0; i < (1<<5); i++) { System.out.println(snowFlake.nextId()); } } }
参考 https://segmentfault.com/a/1190000011282426