生成流水号

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();
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值