一.适用场景:
新增数据后自动生成编码,生成规则为MD + 年月日 + 4位序列号,如MD202310130001
二.场景分析:
此场景需要注意的就是后四位序列号如果使用随机4位数字,极大可能会生成重复的编码,从而影响整个业务,所以最好是使用从0开始自增,不仅避免的随机生成重复编码的可能,而且还方便使用人员根据编码获取到有用信息。
三.功能实现:
private static final String PREFIX = "MD"; // 前缀
private static final String DATE_FORMAT = "yyyyMMdd"; // 年月日格式
/**
* 利用Redis生成编码 (MD202310130001)
* @return
*/
private String generateTemplateNumber(){
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
String currentDate = dateFormat.format(new Date());
//组装Redis的key(自定义字符串 + 当天的时间)
String key = String.format(RedisKeyConstants.TASK_TEMPLATE_CODE, currentDate);
Integer cache = cacheService.getCache(key, Integer.class);
String templateCode = generateTemplateCode(cache);
cacheService.incrBy(key,NumberUtils.INTEGER_ONE,ONE_DAY);
return templateCode;
}
/**
* 根据当前最大值生成编码(可写在工具类中)
* @return
*/
public String generateTemplateCode(Integer num) {
if (ObjectUtils.isEmpty(num)){
num = 0;
}
AtomicInteger sequence = new AtomicInteger(num);
// 获取当前日期
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
String currentDate = dateFormat.format(new Date());
// 生成4位序列号
int currentSequence = sequence.incrementAndGet();
String sequenceStr = String.format("%04d", currentSequence);
// 组装编码
return PREFIX + currentDate + sequenceStr;
}
四.总结:
相比查询数据库中编码的最大值,然后再+1,效率更加高,代码实现难度更加低,因为查询数据库最大值,然后+1,可能要考虑不同天日期的处理,总之,下次遇到有这样类似编码生成的需求,直接用Redis的incrBy是不错之举