@Resource
private RedisTemplate<String, Object> redisTemplate;
/**
* 获取序列号,生成复杂流水号,时间戳加末尾4位自增值,自增值每天都会重置为1,例如:OA_202112260001
*/
public String getIncrement(String key) {
// 获取时间戳
String timeStamp = DateUtil.format(new Date(), "yyyyMMdd");
// 拼接redis缓存的key
String redisKey = "serialNumber:" + key + "_" + timeStamp;
ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
// 获取指定key的序列号
Long increment = valueOperations.increment(redisKey);
// 设置过期失效时间,25小时
redisTemplate.expire(redisKey, 25, TimeUnit.HOURS);
return key + "_" + timeStamp + getSequence(increment);
}
/**
* 最大值位数,超出指定位数则截取,不足则补0
*/
static final int DEFAULT_LENGTH = 4;
/**
* 获取序列化值,例如:传入数值1,返回字符串0001,长度可以自定义
*/
public static String getSequence(long seq) {
String str = String.valueOf(seq);
int len = str.length();
// 取决于业务规模,应该不会到达4
if (len >= DEFAULT_LENGTH) {
return str;
}
int rest = DEFAULT_LENGTH - len;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < rest; i++) {
sb.append('0');
}
sb.append(str);
return sb.toString();
}
// 测试
public static void main(String[] args) {
String personCode = getIncrement("OA");
System.out.println(personCode); // OA_202112260001
}