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