这是一个分布式场景下全局唯一ID生成工具,类似于雪花算法(SnowFlake)。如果你需要生成订单号等类似前缀 yyMMddHHmmss 序列格式的全局唯一性序列可以使用。
结构
{前缀}{yyMMddHHmmss}{workerId}{序列ID}
优点
- 与雪花算法一样,单机执行无需其他中间件做分布式协调
- 代码简单,可自行修改。雪花算法估计很多人还看不太明白吧
局限性
- 需要提前规划序号的最大值,最大值 > 预计单机一秒钟需要生成的序列最大值
最佳实践
通过ZK等维护WORKER_ID
这样可以更好保证唯一性。
代码
代码语言:javascript复制public class BizSequenceGenarator {
private static final String TIME_PATTERN = "yyMMddHHmmss";
private static String[] paddingzeros = new String[]{"","0","00","000","0000","00000","000000","0000000","00000000","000000000"};
private static final String WORKER_ID = String.valueOf(RandomUtils.nextInt(100, 999));
private final AtomicInteger NEXT_COUNTER;
private String prefix;
private int incrMin;
private int incrMax;
public BizSequenceGenarator(String prefix, int incrMax) {
this.prefix = StringUtils.stripToNull(prefix);
if(this.prefix != null)this.prefix = this.prefix.toUpperCase();
this.incrMin = Integer.parseInt("1" String.valueOf(incrMax).substring(1).replaceAll("[0-9]{1}", "0"));
this.incrMax = incrMax;
NEXT_COUNTER = new AtomicInteger(RandomUtils.nextInt(incrMin, incrMax/2));
}
public String next() {
StringBuilder sb = new StringBuilder();
if(prefix != null)sb.append(prefix);
sb.append(DateUtils.format(new Date(),TIME_PATTERN));
sb.append(WORKER_ID);
sb.append(buildIncrNumSequence());
return sb.toString();
}
private String buildIncrNumSequence() {
int next = NEXT_COUNTER.incrementAndGet();
if(incrMax - next < 5){
next = NEXT_COUNTER.updateAndGet( (x) -> x >= incrMax ? RandomUtils.nextInt(incrMin, incrMax/2) : x 1);
}
String seq = String.valueOf(next);
//补0
int len = 5 - seq.length();
if(len > 0){
seq = paddingzeros[len] seq;
}
return seq;
}
public static void main(String[] args) {
BizSequenceGenarator genarator = new BizSequenceGenarator("TEST", 9999);
for (int i = 0; i < 10; i ) {
System.out.println(genarator.next());
}
}
}