public class GenerateFlowNoService { private static final String FORMATTER = "yyMMdd"; @Resource(name = "redisTemplate") private RedisTemplate redisTemplate;
/** * 生成流水号 * 例如:2019年3月21日生成的流水号 prefix19032100001 * * @param prefix 流水号前缀 * @param random 流水号结尾随机数位数 */ public String generateFlowNo(String prefix, int randomNum) { Date now = new Date(); String dateStr = generateDateStr(now); String key = prefix + dateStr; Long random = getRedisAtomicByKey(key); String formatStr = "%0" + randomNum + "d"; String randomStr = String.format(formatStr, random); return key + randomStr; } //获取某key值当前的递增值 private Long getRedisAtomicByKey(String key) { if (!redisTemplate.hasKey(key)) { redisTemplate.opsForValue().set(key, 0, getMilliSecondsRemain(), TimeUnit.MILLISECONDS); } RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory()); Long res = entityIdCounter.getAndIncrement(); return res + 1L; } //获取当天日期字符串 2019年3月21日 为 190321 private String generateDateStr(Date date) { return new SimpleDateFormat(FORMATTER).format(date); } //获取当前时间到当天结束时间的剩余毫秒值 private Long getMilliSecondsRemain() { Calendar curDate = Calendar.getInstance(); Calendar nextDayDate = new GregorianCalendar(curDate.get(Calendar.YEAR), curDate.get(Calendar.MONTH), curDate.get(Calendar.DATE) + 1, 0, 0, 0); return nextDayDate.getTimeInMillis() - curDate.getTimeInMillis(); } }