Redis實現(xiàn)編碼生成規(guī)則方式
適用場景
新增數(shù)據(jù)后自動生成編碼,生成規(guī)則為MD + 年月日 + 4位序列號
如MD202310130001
場景分析
此場景需要注意的就是后四位序列號如果使用隨機(jī)4位數(shù)字,極大可能會生成重復(fù)的編碼,從而影響整個業(yè)務(wù),所以最好是使用從0開始自增,不僅避免的隨機(jī)生成重復(fù)編碼的可能,而且還方便使用人員根據(jù)編碼獲取到有用信息。
功能實現(xiàn)
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(自定義字符串 + 當(dāng)天的時間)
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;
}
/**
* 根據(jù)當(dāng)前最大值生成編碼(可寫在工具類中)
* @return
*/
public String generateTemplateCode(Integer num) {
if (ObjectUtils.isEmpty(num)){
num = 0;
}
AtomicInteger sequence = new AtomicInteger(num);
// 獲取當(dāng)前日期
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;
}總結(jié)
相比查詢數(shù)據(jù)庫中編碼的最大值,然后再+1,效率更加高,代碼實現(xiàn)難度更加低,因為查詢數(shù)據(jù)庫最大值,然后+1,可能要考慮不同天日期的處理,總之,下次遇到有這樣類似編碼生成的需求,直接用Redis的incrBy是不錯之舉
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Redis Cluster集群數(shù)據(jù)分片機(jī)制原理
這篇文章主要介紹了Redis Cluster集群數(shù)據(jù)分片機(jī)制原理,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-04-04

