当前位置:网站首页>基于Redis的分布式ID生成器
基于Redis的分布式ID生成器
2022-07-06 09:17: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算法
- 数据库自增
边栏推荐
- Keyword inline (inline function) usage analysis [C language]
- A possible cause and solution of "stuck" main thread of RT thread
- VIM command line notes
- 互联网协议详解
- RT-Thread的main线程“卡死”的一种可能原因及解决方案
- JS object and event learning notes
- uCOS-III 的特点、任务状态、启动
- 嵌入式启动流程
- Kaggle竞赛-Two Sigma Connect: Rental Listing Inquiries(XGBoost)
- Esp8266 connects to bafayun (TCP maker cloud) through Arduino IED
猜你喜欢

Analysis of charging architecture of glory magic 3pro

Basic knowledge of lithium battery

JS object and event learning notes

sklearn之feature_extraction.text.CountVectorizer / TfidVectorizer

ES6语法总结--上篇(基础篇)

机器学习--线性回归(sklearn)

AMBA、AHB、APB、AXI的理解

几个关于指针的声明【C语言】

MySQL realizes read-write separation

Mall project -- day09 -- order module
随机推荐
AMBA、AHB、APB、AXI的理解
Inline detailed explanation [C language]
优先级反转与死锁
arduino JSON数据信息解析
PyTorch四种常用优化器测试
Rough analysis of map file
Correspondence between STM32 model and contex M
C语言回调函数【C语言】
Programmers can make mistakes. Basic pointers and arrays of C language
列表的使用
C language callback function [C language]
机器学习--决策树(sklearn)
XML文件详解:XML是什么、XML配置文件、XML数据文件、XML文件解析教程
Missing value filling in data analysis (focus on multiple interpolation method, miseforest)
E-commerce data analysis -- User Behavior Analysis
arduino获取数组的长度
电商数据分析--薪资预测(线性回归)
RT-Thread 线程的时间片轮询调度
JS变量类型以及常用类型转换
Several declarations about pointers [C language]