本文主要是介绍雪花算法(非标准实现),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.返回long
2.long有一定意义,前面部分是时间format(两位年份)yyMMddHHmmssSSS
3. 最多支持32台机器,每毫秒产生2048个订单号.
4. 只能用到92年。。哈哈
根据自身情况调整吧~.
import java.text.SimpleDateFormat;
import java.util.Date;public class SnowFlake {/*** 每一部分占用的位数*/private final static long SEQUENCE_BIT = 11; //序列号占用的位数 每台机器每毫秒最多2048笔订单private final static long WORKER_BIT = 5; //机器标识占用的位数 最多32台机器/*** 每一部分的最大值*/private final static long MAX_WORKER_NUM = ~(-1L << WORKER_BIT);private final static long MAX_SEQUENCE = ~(-1L << SEQUENCE_BIT);private static final SimpleDateFormat format = new SimpleDateFormat("yyMMddHHmmssSSS");/*** 每一部分向左的位移*/private final static long WORKER_LEFT = SEQUENCE_BIT;private final long workerId; //机器标识private long sequence = 0L; //序列号private long lastTime = -1L;//上一次时间戳public SnowFlake(long workerId) {if (workerId > MAX_WORKER_NUM || workerId < 0) {throw new IllegalArgumentException("workerId can't be greater than MAX_WORKER_NUM or less than 0");}this.workerId = workerId;}/*** 产生下一个ID*/public synchronized long nextId() {long currStamp = System.currentTimeMillis();if (currStamp < lastTime) {throw new RuntimeException("Clock moved backwards. Refusing to generate id");}if (currStamp == lastTime) {//相同毫秒内,序列号自增sequence = (sequence + 1) & MAX_SEQUENCE;//同一毫秒的序列数已经达到最大if (sequence == 0) {currStamp = waitUntilNextTime();sequence = currStamp % 10;}} else {//使产生的id尾号分布均匀sequence = currStamp % 10;}lastTime = currStamp;//max long: 9223372036854775807, 这个可以用到92年~,可以改为返回String,增加位数~return Long.parseLong(String.format("%s%04d", format.format(new Date(currStamp)), workerId << WORKER_LEFT | sequence));}private long waitUntilNextTime() {long time = System.currentTimeMillis();while (time <= lastTime) {time = System.currentTimeMillis();}return time;}}
这篇关于雪花算法(非标准实现)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!