当前位置:网站首页>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 !
边栏推荐
- Return to blowing marshland -- travel notes of zhailidong, founder of duanzhitang
- Abnova total RNA Purification Kit for cultured cells Chinese and English instructions
- Abnova丨 MaxPab 小鼠源多克隆抗体解决方案
- 1、强化学习基础知识点
- Applet event binding
- 解析创客教育的知识迁移和分享精神
- 重上吹麻滩——段芝堂创始人翟立冬游记
- sort和投影
- Abbkine BCA法 蛋白质定量试剂盒说明书
- 物联网智能家居基本方法实现之经典
猜你喜欢
Prosci LAG-3 recombinant protein specification
Duchefa细胞分裂素丨二氢玉米素 (DHZ)说明书
解析创客教育的知识迁移和分享精神
[quick start of Digital IC Verification] 2. Through an example of SOC project, understand the architecture of SOC and explore the design process of digital system
Norgen AAV提取剂盒说明书(含特色)
Abnova丨血液总核酸纯化试剂盒预装相关说明书
Duchefa丨D5124 MD5A 培养基中英文说明书
Duchefa p1001 plant agar Chinese and English instructions
mysql全面解析json/数组
Introduction to dead letter queue (two consumers, one producer)
随机推荐
mongodb/文档操作
Is it safe to open an account online? Where can I get a low commission?
Where is a good stock account? Is online account manager safe to open an account
Duchefa d5124 md5a medium Chinese and English instructions
当Steam教育进入个性化信息技术课程
Abnova丨DNA 标记高质量控制测试方案
[quick start of Digital IC Verification] 2. Through an example of SOC project, understand the architecture of SOC and explore the design process of digital system
Station B up builds the world's first pure red stone neural network, pornographic detection based on deep learning action recognition, Chen Tianqi's course progress of machine science compilation MLC,
小程序全局配置
Rainbow 5.7.1 supports docking with multiple public clouds and clusters for abnormal alarms
信息学奥赛一本通 1339:【例3-4】求后序遍历 | 洛谷 P1827 [USACO3.4] 美国血统 American Heritage
14、Transformer--VIT TNT BETR
Selenium element information
Graph embedding learning notes
清除app data以及获取图标
Abnova丨血液总核酸纯化试剂盒预装相关说明书
Nprogress plug-in progress bar
E. Singhal and numbers (prime factor decomposition)
Abnova e (diii) (WNV) recombinant protein Chinese and English instructions
Return to blowing marshland -- travel notes of zhailidong, founder of duanzhitang