当前位置:网站首页> Redis唯一ID生成器的实现
Redis唯一ID生成器的实现
2022-07-05 20:35:00 【1024问】
ID的组成部分:
符号位:1bit,永远为0
时间戳:31bit,以秒为单位,可以使用69年
序列号:32bit,秒内的计数器,支持每秒产生2^32个不同ID
生成代码:
public class RedisIdWorker { /** * 开始时间戳 */ private static final long BEGIN_TIMESTAMP = 1640995200L; /** * 序列号的位数 */ private static final int COUNT_BITS = 32; private StringRedisTemplate stringRedisTemplate; //构造方法形式注入 public RedisIdWorker(StringRedisTemplate stringRedisTemplate) { this.stringRedisTemplate = stringRedisTemplate; } 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")); long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date); //3.拼接并返回 return timestamp << COUNT_BITS | count; }}
PS:Redis实现全局唯一id生成
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;/** * 描述: * 唯一ID生成器 * @author jimmy * @create 2020-11-06 16:06 */@Componentpublic class GenerateIDUtil { @Autowired private RedisTemplate redisTemplate; /** * 生成每天的初始Id * @param key * @return */ public String initPrimaryId(String key) { Assert.hasLength(key, "hashName不能为空"); String hashCol = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")); //自定义编号规则 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; } /** * 获取分布式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; } /** * 判断当前时间距离第二天凌晨的秒数 * @return 返回值单位为[s:秒] */ 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; }}
到此这篇关于Redis唯一ID生成器的实现的文章就介绍到这了,更多相关Redis唯一ID生成器内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!
边栏推荐
- 【数字IC验证快速入门】6、Questasim 快速上手使用(以全加器设计与验证为例)
- Mongodb/ document operation
- A way to calculate LNX
- Codeforces Round #804 (Div. 2) - A, B, C
- 3.3 project evaluation
- Scala basics [HelloWorld code parsing, variables and identifiers]
- Ffplay document [easy to understand]
- 鸿蒙os第四次学习
- Kubernetes resource object introduction and common commands (V) - (configmap & Secret)
- js方法传Long类型id值时会出现精确损失
猜你喜欢
. Net distributed transaction and landing solution
Leetcode skimming: binary tree 17 (construct binary tree from middle order and post order traversal sequence)
Leetcode brush questions: binary tree 18 (largest binary tree)
【数字IC验证快速入门】3、数字IC设计全流程介绍
A way to calculate LNX
CTF reverse Foundation
CTF逆向基础
2022北京眼睛健康用品展,护眼产品展,中国眼博会11月举办
小程序页面导航
鸿蒙os第四次学习
随机推荐
【数字IC验证快速入门】8、数字IC中的典型电路及其对应的Verilog描述方法
Propping of resources
Mongodb basic exercises
Leetcode brush questions: binary tree 11 (balanced binary tree)
[C language] three implementations of quick sorting and optimization details
Nprogress plug-in progress bar
go 文件路径操作
物联网智能家居基本方法实现之经典
【数字IC验证快速入门】2、通过一个SoC项目实例,了解SoC的架构,初探数字系统设计流程
ROS2专题【01】:win10上安装ROS2
CVPR 2022 | 常见3D损坏和数据增强
Hong Kong stocks will welcome the "best ten yuan store". Can famous creative products break through through the IPO?
sort和投影
Minimum commission for stock trading account opening, where to open an account with low commission? Is it safe to open an account on your mobile phone
2.8、项目管理过程基础知识
National Eye Care Education Conference, 2022 the Fourth Beijing International Youth eye health industry exhibition
信息学奥赛一本通 1337:【例3-2】单词查找树 | 洛谷 P5755 [NOI2000] 单词查找树
本季度干货导航 | 2022年Q2
全国爱眼教育大会,2022第四届北京国际青少年眼健康产业展会
Leetcode(695)——岛屿的最大面积