当前位置:网站首页>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 !
边栏推荐
- mysql全面解析json/数组
- Which securities is better for securities account opening? Is online account opening safe?
- 王老吉药业“关爱烈日下最可爱的人”公益活动在南京启动
- Norgen AAV extractant box instructions (including features)
- 插值查找的简单理解
- CVPR 2022 | common 3D damage and data enhancement
- Abnova丨 CD81单克隆抗体相关参数和应用
- AI automatically generates annotation documents from code
- 小程序页面导航
- When JS method passes long type ID value, precision loss will occur
猜你喜欢
Make Jar, Not War
Abnova丨培养细胞总 RNA 纯化试剂盒中英文说明书
CVPR 2022 | common 3D damage and data enhancement
Duchefa丨低熔点琼脂糖 PPC中英文说明书
PyTorch 1.12发布,正式支持苹果M1芯片GPU加速,修复众多Bug
Duchefa丨D5124 MD5A 培养基中英文说明书
14、Transformer--VIT TNT BETR
【刷题记录】1. 两数之和
Make Jar, Not War
Welcome to the game and win rich bonuses: Code Golf Challenge officially launched
随机推荐
台风来袭!建筑工地该如何防范台风!
Abnova丨 CD81单克隆抗体相关参数和应用
CTF reverse Foundation
2020 CCPC Weihai - A. golden spirit (thinking), D. ABC project (big number decomposition / thinking)
19 Mongoose模块化
物联网智能家居基本方法实现之经典
How to renew NPDP? Here comes the operation guide!
Abnova total RNA Purification Kit for cultured cells Chinese and English instructions
model方法
14、Transformer--VIT TNT BETR
CVPR 2022 | common 3D damage and data enhancement
Specification of protein quantitative kit for abbkine BCA method
Mongodb basic exercises
3.3 project evaluation
Leetcode (695) - the largest area of an island
全国爱眼教育大会,2022第四届北京国际青少年眼健康产业展会
信息学奥赛一本通 1338:【例3-3】医院设置 | 洛谷 P1364 医院设置
Ros2 topic [01]: installing ros2 on win10
鸿蒙os第四次学习
小程序页面导航