当前位置:网站首页>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 !
边栏推荐
- Abbkine trakine F-actin Staining Kit (green fluorescence) scheme
- Simple understanding of interpolation search
- 2022北京眼睛健康用品展,护眼产品展,中国眼博会11月举办
- Typhoon is coming! How to prevent typhoons on construction sites!
- Duchefa细胞分裂素丨二氢玉米素 (DHZ)说明书
- Leetcode (695) - the largest area of an island
- Composition of applet code
- The Chinese Academy of Management Sciences gathered industry experts, and Fu Qiang won the title of "top ten youth" of think tank experts
- 2022 Beijing eye health products exhibition, eye care products exhibition, China eye Expo held in November
- Informatics Orsay all in one 1339: [example 3-4] find the post order traversal | Valley p1827 [usaco3.4] American Heritage
猜你喜欢

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,

Return to blowing marshland -- travel notes of zhailidong, founder of duanzhitang

Hongmeng OS' fourth learning

14、Transformer--VIT TNT BETR

Kubernetes resource object introduction and common commands (V) - (configmap & Secret)

Abnova CRISPR spcas9 polyclonal antibody protocol

Abbkine丨TraKine F-actin染色试剂盒(绿色荧光)方案

Frequent MySQL operations cause table locking problems
![信息学奥赛一本通 1339:【例3-4】求后序遍历 | 洛谷 P1827 [USACO3.4] 美国血统 American Heritage](/img/f0/0f985425bd61d9852af0b5fd7307ee.png)
信息学奥赛一本通 1339:【例3-4】求后序遍历 | 洛谷 P1827 [USACO3.4] 美国血统 American Heritage

2.8 basic knowledge of project management process
随机推荐
Sort and projection
CVPR 2022 | 常见3D损坏和数据增强
IC popular science article: those things about Eco
Duchefa d5124 md5a medium Chinese and English instructions
Duchefa丨低熔点琼脂糖 PPC中英文说明书
Common view container class components
Abnova 环孢素A单克隆抗体,及其研究工具
Return to blowing marshland -- travel notes of zhailidong, founder of duanzhitang
Practical demonstration: how can the production research team efficiently build the requirements workflow?
mongodb/文档操作
Specification of protein quantitative kit for abbkine BCA method
Informatics Orsay all in one 1339: [example 3-4] find the post order traversal | Valley p1827 [usaco3.4] American Heritage
ProSci LAG3抗体的化学性质和应用说明
王老吉药业“关爱烈日下最可爱的人”公益活动在南京启动
Applet project structure
NPDP如何续证?操作指南来了!
Applet event binding
Fundamentals - configuration file analysis
Typhoon is coming! How to prevent typhoons on construction sites!
Mongodb basic exercises