需求描述:自增主鍵的格式為 業務序列+當前日期+從00001開始自增
//redis實現按業務+日期+自增
//輸出結果為:biz2020021800001、biz2020021800002、biz2020021800003的形式
@Test
public void testJedis(){
SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
Date date=new Date();
String formatDate=sdf.format(date);
//業務編碼+日期做為redis的key
String key = "biz" + formatDate;
//關鍵是使用RedisAtomicLong類來實現,能夠保證原子性
RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
//取出redis中存放的值,從1開始自增
Long increment = entityIdCounter.incrementAndGet();
//將值轉換為指定位數
DecimalFormat df=new DecimalFormat("00000");//五位序列號
String value = df.format(increment);
//鍵與值拼接做為自增主鍵
System.out.println(key + value);
}
以上是單線程的情況進行測試,也可以通過下面多線程的方式進行測試
public void testMoreThread()throws Exception{
ExecutorService executorService = Executors.newFixedThreadPool(100);
for(int i=1;i<=1000;i++){
executorService.execute(new Runnable() {
@Override
public void run() {
System.out.println("當前線程為:" + Thread.currentThread().getName());
SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
Date date=new Date();
String formatDate=sdf.format(date);
//業務編碼+日期做為redis的key
String key = "biz" + formatDate;
RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
//取出redis中存放的值,從1開始自增
Long increment = entityIdCounter.incrementAndGet();
//將值轉換為指定位數
DecimalFormat df=new DecimalFormat("00000");//五位序列號
String value = df.format(increment);
//鍵與值拼接做為自增主鍵
System.out.println("業務主鍵為:"+key + value);
}
});
}
//一定要有這兩行代碼,否則上邊的for循環中的線程還沒有執行完,線程池就關閉了,然后就會報錯連接不上redis
Thread.sleep(5000); //模擬等待執行結束
executorService.shutdown();
}