You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

93 lines
2.7 KiB

2 years ago
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;
2 years ago
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){
2 years ago
try {
String key = "code_index:"+sourceKey.getCode();
2 years ago
RedisService redisService = SpringUtils.getBean(RedisService.class);
Long value = redisService.getLong(key);
if(value==null){
redisService.set(key,1);
value = 1L;
}else {
value++;
}
if(value>8000000){
redisService.set(key,1);
}else {
redisService.set(key,value);
}
2 years ago
LocalDate localDateTime = LocalDate.now();
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd");
String localTime = df.format(localDateTime);
String appendStr = digits32(value);
return localTime.substring(2) + appendStr;
2 years ago
} 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);
}
2 years ago
}