当前位置:网站首页>Implementation of redis unique ID generator
Implementation of redis unique ID generator
2022-07-05 20:43:00 【1024 questions】
ID Component part :
Sign bit :1bit, For ever 0
Time stamp :31bit, In seconds , have access to 69 year
Serial number :32bit, Seconds counter , Support generation per second 2^32 Different ID
The generated code :
public class RedisIdWorker { /** * Start timestamp */ private static final long BEGIN_TIMESTAMP = 1640995200L; /** * Number of digits of serial number */ private static final int COUNT_BITS = 32; private StringRedisTemplate stringRedisTemplate; // Construction method form injection public RedisIdWorker(StringRedisTemplate stringRedisTemplate) { this.stringRedisTemplate = stringRedisTemplate; } public long nextId(String keyPrefix){ //1. Generate timestamps LocalDateTime now = LocalDateTime.now(); long nowSecond = now.toEpochSecond(ZoneOffset.UTC); long timestamp = nowSecond - BEGIN_TIMESTAMP; //2. Generate serial number // 2.1 Get current date , Accurate to the sky String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd")); long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date); //3. Splice and return return timestamp << COUNT_BITS | count; }}
PS:Redis Achieve global uniqueness id Generate
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.stereotype.Component;import org.springframework.util.Assert;import java.time.LocalDate;import java.time.format.DateTimeFormatter;import java.util.Calendar;import java.util.concurrent.TimeUnit;/** * describe : * only ID generator * @author jimmy * @create 2020-11-06 16:06 */@Componentpublic class GenerateIDUtil { @Autowired private RedisTemplate redisTemplate; /** * Generate daily initial Id * @param key * @return */ public String initPrimaryId(String key) { Assert.hasLength(key, "hashName Can't be empty "); String hashCol = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")); // Custom numbering sequence String hashColVal = hashCol + "00001";// redisTemplate.opsForHash().putIfAbsent(hashName, hashCol, hashColVal); Long expiresTime = getSecondsNextEarlyMorning(); redisTemplate.opsForValue().set(key, Long.valueOf(hashColVal), expiresTime, TimeUnit.SECONDS); return hashColVal; } /** * Get distributed Id * @param key * @return */ public String getPrimaryId(String key) { String id = ""; if(redisTemplate.hasKey(key)){ // redisTemplate.opsForValue().get(key); // redisTemplate.delete(key); id = String.valueOf(redisTemplate.opsForValue().increment(key, 1)); } else { id = initPrimaryId(key); } return id; } /** * Judge the number of seconds from the current time to the early morning of the next day * @return The unit of return value is [s: second ] */ public Long getSecondsNextEarlyMorning() { Calendar cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_YEAR, 1); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.MILLISECOND, 0); return (cal.getTimeInMillis() - System.currentTimeMillis()) / 1000; }}
This is about Redis only ID This is the end of the article on the implementation of the generator , More about Redis only ID Please search the previous articles of SDN or continue to browse the related articles below. I hope you will support SDN more in the future !
边栏推荐
- mongodb文档间关系
- PyTorch 1.12发布,正式支持苹果M1芯片GPU加速,修复众多Bug
- Make Jar, Not War
- [Yugong series] go teaching course in July 2022 004 go code Notes
- 信息学奥赛一本通 1339:【例3-4】求后序遍历 | 洛谷 P1827 [USACO3.4] 美国血统 American Heritage
- Schema and model
- Composition of applet code
- E. Singhal and numbers (prime factor decomposition)
- 1. Strengthen learning basic knowledge points
- 资源道具化
猜你喜欢
Abnova CRISPR spcas9 polyclonal antibody protocol
PHP反序列化+MD5碰撞
Abnova DNA marker high quality control test program
CTF reverse Foundation
如何让化工企业的ERP库存账目更准确
线程池的使用
Duchefa d5124 md5a medium Chinese and English instructions
Norgen AAV提取剂盒说明书(含特色)
Duchefa p1001 plant agar Chinese and English instructions
[record of question brushing] 1 Sum of two numbers
随机推荐
2020 CCPC Weihai - A. golden spirit (thinking), D. ABC project (big number decomposition / thinking)
1. Strengthen learning basic knowledge points
Hongmeng OS' fourth learning
Document method
中国管理科学研究院凝聚行业专家,傅强荣获智库专家“十佳青年”称号
Fundamentals - configuration file analysis
[Yugong series] go teaching course in July 2022 004 go code Notes
Duchefa丨MS培养基含维生素说明书
Return to blowing marshland -- travel notes of zhailidong, founder of duanzhitang
Abnova DNA marker high quality control test program
【愚公系列】2022年7月 Go教学课程 004-Go代码注释
Common view container class components
渗透创客精神文化转化的创客教育
Informatics Olympiad 1340: [example 3-5] extended binary tree
小程序代码的构成
小程序页面导航
Pytorch 1.12 was released, officially supporting Apple M1 chip GPU acceleration and repairing many bugs
物联网智能家居基本方法实现之经典
手机开户股票开户安全吗?我家比较偏远,有更好的开户途径么?
Informatics Orsay all in one 1339: [example 3-4] find the post order traversal | Valley p1827 [usaco3.4] American Heritage