使用redis批量生成主键(订单)Id
生活随笔
收集整理的這篇文章主要介紹了
使用redis批量生成主键(订单)Id
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
前言:
在多線程、高并發(fā)情況下,某些業(yè)務(wù)場景需要創(chuàng)建唯一標(biāo)識的主鍵(訂單)Id;通常情況下都是一個請求創(chuàng)建一個,考慮到性能和QPS我們會提前生成好一堆隨機(jī)id保存到redis;從redis進(jìn)行poll。
1、創(chuàng)建一個redis隊列服務(wù)
//redis 公共操作服務(wù) public class RedisPublicService {public Redisson redisson;private RQueue<Long> pkQueue;public void init() {pkQueue=redisson.getQueue("GENERATOR_PRIMARY_KEY"); }public RQueue<Long> getPkQueue(){return pkQueue;} }復(fù)制代碼2、創(chuàng)建線程進(jìn)行生成批量id
public class GeneratePrimaryKeyTask extends Thread{private RedisPublicService redisService;private final int cnt=10000;private final Random random=new Random();public Long getPrimaryId() {//length=18 ;變量賦隨機(jī)值1000-9999return System.currentTimeMillis()*100000+random.nextInt(99999);}public Set<Long> getPrimaryIds(int num) {Set<Long> ids = new HashSet<Long>();while(ids.size()!=num){ids.add(getPrimaryId());}return ids;}public void startup(){this.start();}Logger log = LoggerFactory.getLogger(GeneratePrimaryKeyTask.class);("static-access")public void run(){RQueue<Long> que=redisService.getPkQueue();while(true){if(que.size()<cnt){ //當(dāng)隊列的數(shù)量小于cnt就會生成插入que.addAll(getPrimaryIds(cnt));log.info("create pk to redis current amount:"+que.size());}else{try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}}}} }復(fù)制代碼使用方法:
RQueue<Long> pkQueue = redisson.getQueue("GENERATOR_PRIMARY_KEY");Long key = pkQueue.poll();復(fù)制代碼以上就是生成批量id的簡單使用~~
?
轉(zhuǎn)載于:https://juejin.im/post/5cf60203f265da1b6c5f624c
總結(jié)
以上是生活随笔為你收集整理的使用redis批量生成主键(订单)Id的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 软件工程——认识方法、模型、工具和技术
- 下一篇: class类初始化之后调用赋值问题记录