当前位置:网站首页>基於Redis的分布式ID生成器
基於Redis的分布式ID生成器
2022-07-06 12:12:00 【阿杆.】
基於Redis的分布式ID生成器
ID自增策略
- 每天一個key,方便統計訂單量
- ID構造是 時間戳 + 計數器
ID的組成部分

- 符號比特:1bit,永遠為0
- 時間戳:31bit,以秒為單比特,從2022年1月開始計數,可以使用68年,也可以根據需求,修改為每分鐘、每小時或每天的計數器,可以增大可用時間。
- 序列號:32bit,每天的計數器,支持每天產生2^32個不同ID,也可以根據需求,修改為每小時、每分鐘或每秒的計數器,但需要和時間戳相配合,可以增大ID數量。
這裏是以秒為單比特的時間戳和以天為單比特的序列化計數器組成的ID生成器。
package cn.sticki.common.redis.utils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
/** * @author 阿杆 * @version 1.0 * @date 2022/6/20 20:29 */
@Component
public class RedisIdGenerator {
/** * 開始時間戳 */
private static final long BEGIN_TIMESTAMP = 1640995200L;
/** * 序列號的比特數 */
private static final int COUNT_BITS = 32;
private final RedisTemplate<String, Long> redisTemplate;
public RedisIdGenerator(RedisTemplate<String, Long> redisTemplate) {
this.redisTemplate = redisTemplate;
}
@SuppressWarnings("ConstantConditions")
public long nextId(String keyPrefix) {
// 1. 生成時間戳
LocalDateTime now = LocalDateTime.now();
long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
long timestamp = nowSecond - BEGIN_TIMESTAMP;
// 2. 生成序列號
// 2.1 獲取當前日期,精確到天
String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
// 2.2 獲取redis自增長值
long increment = redisTemplate.opsForValue().increment("id:" + keyPrefix + ":" + date);
// 3. 拼接並返回
return increment << COUNT_BITS | timestamp;
}
}
其他全局唯一ID生成策略
- UUID
- Redis自增
- snowflake算法
- 數據庫自增
边栏推荐
- XML file explanation: what is XML, XML configuration file, XML data file, XML file parsing tutorial
- arduino UNO R3的寄存器写法(1)-----引脚电平状态变化
- Oppo vooc fast charging circuit and protocol
- R & D thinking 01 ----- classic of embedded intelligent product development process
- Imgcat usage experience
- VSCode基础配置
- There are three iPhone se 2022 models in the Eurasian Economic Commission database
- Redis interview questions
- ESP8266通过Arduino IDE连接Onenet云平台(MQTT)
- JS regular expression basic knowledge learning
猜你喜欢
随机推荐
The first simple case of GNN: Cora classification
Working principle of genius telephone watch Z3
电商数据分析--薪资预测(线性回归)
OPPO VOOC快充电路和协议
PyTorch四种常用优化器测试
Linux Yum install MySQL
Cannot change version of project facet Dynamic Web Module to 2.3.
map文件粗略分析
机器学习--决策树(sklearn)
GNN的第一个简单案例:Cora分类
Priority inversion and deadlock
XML file explanation: what is XML, XML configuration file, XML data file, XML file parsing tutorial
MP3mini播放模块arduino<DFRobotDFPlayerMini.h>函数详解
OSPF message details - LSA overview
VSCode基础配置
关键字 inline (内联函数)用法解析【C语言】
Arm pc=pc+8 is the most understandable explanation
Basic knowledge of lithium battery
Oppo vooc fast charging circuit and protocol
Detailed explanation of Union [C language]









