java雪花算法改造(带⽇期格式)毫秒级import java.util.Date;
java时间日期格式转换public class MySnowFlake {
private long lastTimestamp = -1L;
private int sequence;
private final int sequenceMask=999;
public MySnowFlake(Integer sequence){
if (sequence<0||sequence>sequenceMask){
throw new IllegalArgumentException(
"sequence can't be greater than 999 or lesser than 0"
);
}
this.sequence=sequence;
}
public synchronized String nextId() {
String result="";
long timestamp = timeGen();
if (timestamp < lastTimestamp) {
"clock is moving backwards. Rejecting requests until %d.", lastTimestamp);
throw new RuntimeException(
String.format("Clock moved backwards. Refusing to generate id for %d milliseconds",
lastTimestamp - timestamp));
}
if (lastTimestamp == timestamp) {
sequence = (sequence + 1) % sequenceMask;
if (sequence == 0) {
timestamp = tilNextMillis(lastTimestamp);
}
} else {
//从0开始
sequence = 0;
}
lastTimestamp=timestamp;
Date date1 =new Date(lastTimestamp);
SimpleDateFormat sd =new SimpleDateFormat("yyyyMMdd-HH-mm-ss-SSS");
String format = sd.format(date1);
result=format+"-"+sequence;
return result;
}
private long timeGen(){
return System.currentTimeMillis();
}
/**
* 等待到下⼀毫秒
* @param lastTimestamp
* @return
*/
private long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
public static void main(String[] args) {
MySnowFlake mySnowFlake =new MySnowFlake(1);        for (int i=0;i<40;i++){
String s = Id();
System.out.println(s);
}
}
}
20210706-20-14-47-564-0
20210706-20-14-47-605-0
20210706-20-14-47-605-1
20210706-20-14-47-605-2
20210706-20-14-47-606-0
20210706-20-14-47-606-1
20210706-20-14-47-606-2
20210706-20-14-47-606-3
20210706-20-14-47-606-4
20210706-20-14-47-607-0
20210706-20-14-47-607-1
20210706-20-14-47-607-2
20210706-20-14-47-607-3
20210706-20-14-47-607-4
20210706-20-14-47-607-5
20210706-20-14-47-608-0
20210706-20-14-47-608-1
20210706-20-14-47-608-2
20210706-20-14-47-608-3
20210706-20-14-47-609-0
20210706-20-14-47-609-1
20210706-20-14-47-609-2
20210706-20-14-47-609-3
20210706-20-14-47-609-4
20210706-20-14-47-610-0
20210706-20-14-47-610-1
20210706-20-14-47-610-2
20210706-20-14-47-610-3
20210706-20-14-47-611-0
20210706-20-14-47-611-1
20210706-20-14-47-611-2
20210706-20-14-47-611-3
20210706-20-14-47-611-4
20210706-20-14-47-611-5
20210706-20-14-47-611-6
20210706-20-14-47-611-7
20210706-20-14-47-612-0
20210706-20-14-47-612-1
20210706-20-14-47-612-2
20210706-20-14-47-612-3
Process finished with exit code 0

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。