生成唯一序列号

private static final String SERIAL_CODE_KEY ="_serial_code_key";
private static final String BATCH_CODE_ORDER_DATE_KEY = "batch_code_date";

@Autowired
JRedisUtils jredisUtils;



 /**
 *
 * [@param](https://my.oschina.net/u/2303379) prefix  编号前缀
 * [@param](https://my.oschina.net/u/2303379) maximum  编号最大长度,包含前缀在一起的长度
 * [@param](https://my.oschina.net/u/2303379) codeUse  序列号的用途,该参数用于表示不同Redis的Key,其中可以包含业务机构
 * [@return](https://my.oschina.net/u/556800)
 * @throws Exception
 */
public  String generateCode(String prefix, int maximum, String codeUse) throws Exception{
    StringBuilder stringBuilder;
    if(Objects.isNull(maximum)||maximum<=0){
        maximum=20;
    }
    if(StringUtils.isBlank(prefix)||prefix.length()>maximum||StringUtils.isBlank(codeUse)){
        throw new DescribeException(StatusConstant.EXCEPTION,"获取序列号异常,总长度应该大于前缀长度");
    }
    if(StringUtils.isBlank(codeUse)){
        throw new DescribeException(StatusConstant.EXCEPTION,"获取序列号异常,序列号用途不能为空");
    }
    try {
        int codeLength=maximum-prefix.length();
		//最大值
        int maxRule=(int)Math.pow(10,codeLength)-1;
        StringBuilder codeStr=new StringBuilder(codeUse).append(SERIAL_CODE_KEY);
        stringBuilder = new StringBuilder(prefix);
        String code=codeStr.toString();
        if (!jredisUtils.exists(code)) {
            jredisUtils.incrBy(code,1);
            Calendar todayEnd = Calendar.getInstance();
            todayEnd.set(Calendar.HOUR_OF_DAY, 23);
            todayEnd.set(Calendar.MINUTE, 59);
            todayEnd.set(Calendar.SECOND, 59);
            todayEnd.set(Calendar.MILLISECOND, 999);
            long currentTime=System.currentTimeMillis();
            long todayEndTime=todayEnd.getTimeInMillis();
            long time=(todayEndTime-currentTime)/1000;
            jredisUtils.expire(code,Long.valueOf(time).intValue());
            logger.info("<<Key:{},失效时间:{},序列号最大值:{}>>",code,time,maxRule);
            stringBuilder.append(String.format("%0"+codeLength+"d",1));
        }else{
            long serialNum = jredisUtils.incrBy(code,1);
            if(serialNum>maxRule){
                logger.error("当日编号超过最大长度");
                throw new DescribeException(StatusConstant.EXCEPTION,"当日编号超过最大长度");
            }
            stringBuilder.append(String.format("%0"+codeLength+"d",serialNum));
        }
    } catch (Exception e) {
        logger.error("生成序列号异常,e={}",e);
        throw new DescribeException(StatusConstant.EXCEPTION,"获取序列号异常");
    }
    return stringBuilder.toString();
}

转载于:https://my.oschina.net/u/3855710/blog/2218566

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值