public class GeneratorCode {
private static final FastDateFormat PATTERN = FastDateFormat.getInstance("yyyyMMddHHmmss");
private static ThreadLocal<StringBuilder> threadLocal = new ThreadLocal<>();
/**
* @description 生成编码, 标识+YY+MM+DD+HH+mm+ss+7位数+2位随机
* @param flag
* @return String
*/
public static String getOrderCode(String flag) {
try {
// 取系统当前时间作为订单号前半部分
StringBuilder builder = new StringBuilder(flag + PATTERN.format(Instant.now().toEpochMilli()));
// 7 位随机数
builder.append(ThreadLocalRandom.current().nextLong(1000000, 9999999));
// 2位随机数
builder.append(ThreadLocalRandom.current().nextLong(10, 99));
threadLocal.set(builder);
}catch (Exception e) {
log.error("生成编码异常: {} , {}", e.getMessage(), e);
}
return threadLocal.get().toString();
}
}
以上工具类可以工具自己的需求,改变相应的实现策略