|
|
|
package com.qs.serve.common.util;
|
|
|
|
|
|
|
|
import cn.hutool.core.util.IdUtil;
|
|
|
|
import com.qs.serve.common.framework.redis.RedisService;
|
|
|
|
import lombok.AllArgsConstructor;
|
|
|
|
import lombok.Getter;
|
|
|
|
import org.springframework.beans.BeansException;
|
|
|
|
|
|
|
|
import java.time.LocalDate;
|
|
|
|
import java.time.LocalDateTime;
|
|
|
|
import java.time.format.DateTimeFormatter;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* 生成编号
|
|
|
|
* @author YenHex
|
|
|
|
* @since 2023/6/25
|
|
|
|
*/
|
|
|
|
public class CodeGenUtil {
|
|
|
|
|
|
|
|
@Getter
|
|
|
|
@AllArgsConstructor
|
|
|
|
public enum SourceKey{
|
|
|
|
CostApply("cost_apply"),
|
|
|
|
Activity("activity"),
|
|
|
|
Verification("verification"),
|
|
|
|
Policy("policy"),
|
|
|
|
PolicyItem("policy_item");
|
|
|
|
private String code;
|
|
|
|
}
|
|
|
|
|
|
|
|
public static String generate(SourceKey sourceKey){
|
|
|
|
try {
|
|
|
|
String key = "code_index:"+sourceKey.getCode();
|
|
|
|
RedisService redisService = SpringUtils.getBean(RedisService.class);
|
|
|
|
Long value = redisService.getLong(key);
|
|
|
|
if(value==null){
|
|
|
|
redisService.set(key,1);
|
|
|
|
value = 1L;
|
|
|
|
}else {
|
|
|
|
value++;
|
|
|
|
}
|
|
|
|
if(value>10000){
|
|
|
|
redisService.set(key,1);
|
|
|
|
}else {
|
|
|
|
redisService.set(key,value);
|
|
|
|
}
|
|
|
|
LocalDate localDateTime = LocalDate.now();
|
|
|
|
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd");
|
|
|
|
String localTime = df.format(localDateTime);
|
|
|
|
String appendStr = digits32(value);
|
|
|
|
StringBuilder appendZeros = new StringBuilder();
|
|
|
|
for (int i = appendStr.length(); i < 3; i++) {
|
|
|
|
appendZeros.append("0");
|
|
|
|
}
|
|
|
|
return localTime.substring(2) + appendZeros + appendStr;
|
|
|
|
} catch (BeansException e) {
|
|
|
|
e.printStackTrace();
|
|
|
|
}
|
|
|
|
return IdUtil.getSnowflakeNextIdStr();
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* 32个字符,用来表示32进制
|
|
|
|
*/
|
|
|
|
final static char[] digits = {
|
|
|
|
'0' , '1' , '2' , '3' , '4' , '5' ,
|
|
|
|
'6' , '7' , '8' , '9' , 'A' , 'B' ,
|
|
|
|
'C' , 'D' , 'E' , 'F' , 'G' , 'H' ,
|
|
|
|
'J' , 'K' , 'L' , 'M' , 'N' , 'P' ,
|
|
|
|
'Q' , 'R' , 'T' , 'U' , 'V' , 'W' ,
|
|
|
|
'X' , 'Y'
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* 10=>32
|
|
|
|
* @param val
|
|
|
|
* @return
|
|
|
|
*/
|
|
|
|
static String digits32(long val) {
|
|
|
|
// 32=2^5=二进制100000
|
|
|
|
int shift = 5;
|
|
|
|
// numberOfLeadingZeros 获取long值从高位连续为0的个数,比如val=0,则返回64
|
|
|
|
// 此处mag=long值二进制减去高位0之后的长度
|
|
|
|
int mag = Long.SIZE - Long.numberOfLeadingZeros(val);
|
|
|
|
int len = Math.max(((mag + (shift - 1)) / shift), 1);
|
|
|
|
char[] buf = new char[len];
|
|
|
|
do {
|
|
|
|
// &31相当于%32
|
|
|
|
buf[--len] = digits[((int) val) & 31];
|
|
|
|
val >>>= shift;
|
|
|
|
} while (val != 0 && len > 0);
|
|
|
|
return new String(buf);
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
}
|