当前位置:网站首页>Redis implements a globally unique ID
Redis implements a globally unique ID
2022-06-24 09:05:00 【Bulst】
List of articles
In distributed system, because of the cross process and cross system , In some scenes , We need to generate globally unique ID, For example, the order system , Concurrent , Different systems need to generate different orders at the same time ID It is convenient for subsequent order placing and query .
Globally unique ID Generation strategy
- UUID
- Redis Self increasing
- snowflake Algorithm
- Database autoincrement
- Baidu open source UidGenerator
- Meitu comments Leaf
Redis Self increasing ID Strategy
- One a day key, It is convenient to count the order quantity
- ID structure : Time stamp + Counter

ID Component part :
- Sign bit :1bit, For ever 0, It means a positive number
- Time stamp :31bit, Maximum 2147483648 second , Probably 69 year
- Serial number :32bit, Seconds counter , Support generation per second 2^32 Different ID
utilize redis Generate globally unique ID, Actually redis The role played is a counter , Facilitate subsequent statistics .
- advantage : High performance , High concurrency , Uniqueness , Incremental , Security .
- shortcoming : Need to rely on redis To achieve
Code implementation
/** * @author issavior */
@Component
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 final StringRedisTemplate stringRedisTemplate;
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"));
// 2.2. Self growth
Long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);
// 3. Splice and return
return timestamp << COUNT_BITS | (count == null ? 0 : count);
}
/** * obtain 2022 year 1 month 1 Number 0 spot 0 when 0 Minute timestamp * @param args */
public static void main(String[] args) {
LocalDateTime startLocalTime = LocalDateTime.of(2022, 1, 1, 0, 0, 0);
long startTime = startLocalTime.toEpochSecond(ZoneOffset.UTC);
System.out.println(startTime);
LocalDateTime now = LocalDateTime.now();
String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd:HH:mm"));
System.out.println(date);
}
}
边栏推荐
- 解决:模型训练时loss出现nan
- 2022 spring recruitment interview summary
- [quantitative investment] discrete Fourier transform to calculate array period
- 十二、所有功能实现效果演示
- Why can ping fail while traceroute can
- I heard that you are still spending money to buy ppt templates from the Internet?
- 【使用 PicGo+腾讯云对象存储COS 作为图床】
- KaFormer个人笔记整理
- 4274. suffix expression
- 什么是图神经网络?图神经网络有什么用?
猜你喜欢

【PyTorch基础教程30】DSSM双塔模型代码解析

【量化投资】离散傅里叶变换求数组周期

【LeetCode】415. 字符串相加

【牛客】把字符串转换成整数

JS to find and update the specified value in the object through the key

eBanb B1手环刷固件异常中断处理

基于QingCloud的 “房地一体” 云解决方案

2022-06-23: given a nonnegative array, select any number to make the maximum cumulative sum a multiple of 7, and return the maximum cumulative sum. N is larger, to the 5th power of 10. From meituan. 3

Squid代理服务器应用

MySQL | view notes on Master Kong MySQL from introduction to advanced
随机推荐
Implementation process of tcpdump packet capturing
What is graph neural network? Figure what is the use of neural networks?
MySQL | 视图《康师傅MySQL从入门到高级》笔记
Change SSH port number
How to import MDF and LDF files into MySQL workbench
“不平凡的代理初始值设定不受支持”,出现的原因及解决方法
Ordinary people have no education background. Can they earn more than 10000 yuan a month by Self-taught programming?
Pytorch读入据集(典型数据集及自定义数据集两种模式)
Mba-day25 best value problem - application problem
Leetcode -- wrong set
数据中台:数据治理概述
GradScaler MaxClipGradScaler
Data midrange: analysis of full stack technical architecture of data midrange, with industry solutions
2022-06-23: given a nonnegative array, select any number to make the maximum cumulative sum a multiple of 7, and return the maximum cumulative sum. N is larger, to the 5th power of 10. From meituan. 3
Scheme of alcohol concentration tester based on single chip microcomputer
Telnet port login method with user name for liunx server
Threejs glow channel 01 (unrealbroompass & layers)
十二、所有功能实现效果演示
A tip to read on Medium for free
The list of open source summer winners has been publicized, and the field of basic software has become a hot application this year