通常需要seq时很多时候一般直接用数据库或者第三方服务来满足我们的需求。但在特定的时候我们并不想引入太多的三方服务,也许我们仅仅只想要做一个demo,这个demo中需要一个序列号,这个自己实现起来有很多方式,并且也不难。但是如果有直接可以拿来用的,为什么还要再造一个轮子呢?
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 生成递增序列号-线程安全
* @java version 8
* @author cosmozhu
* @mail zhuchao1103@gmail.com
* @site https://www.cosmozhu.fun
*/
public class GenSequence {
private final static AtomicInteger ai = new AtomicInteger(0);
/**
* 生成格式为yyyyMMddHHmmssxxxxx数字型序列号
* @param scale 1-10之间的整数
* @return 序列号
*/
public static String getSeq(int scale) {
if (scale < 0 || scale > 10) {
throw new IllegalArgumentException("scale应为[1-10]之间的整数。");
}
LocalDateTime now = LocalDateTime.now();
StringBuilder dateTime = new StringBuilder(now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
ai.compareAndSet(Integer.MAX_VALUE, 0);
int incrementAndGet = ai.incrementAndGet();
StringBuilder str = new StringBuilder(String.format("%0"+scale+"d", incrementAndGet));
return dateTime.append(str.substring(str.length()-scale, str.length())).toString();
}
public static void main(String[] args) {
for(int i=0;i<4;i++) {
System.out.println(GenSequence.getSeq(1));
}
}
}
作者:cosmozhu --90后的老父亲,专注于保护地球的程序员
欢迎转载,转载时请注明出处。