使用AtomicInteger类获取自增流水号,重启服务则重新开始自增,代码如下:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.atomic.AtomicInteger;
public class AutoNumberGenerator {
private final DateTimeFormatter dateFormat;
private final int serialNumberBound;
private final AtomicInteger serialNumber = new AtomicInteger(1);
private LocalDate lastDate = LocalDate.now();
public AutoNumberGenerator(DateTimeFormatter dateFormat, int serialNumberBound) {
this.dateFormat = dateFormat;
this.serialNumberBound = serialNumberBound;
}
/**
* 生成编号 yyyyMMddXXXX
*
* @return 格式:202001010001
*/
public String generate() {
LocalDate now = LocalDate.now();
if (now.equals(lastDate)) {
int serial = serialNumber.getAndUpdate(n -> n > serialNumberBound ? 1 : n + 1);
return now.format(dateFormat) + String.format("%04d", serial);
} else {
lastDate = now;
serialNumber.set(1);
return now.format(dateFormat) + "0001";
}
}
}