当前位置:网站首页> 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生成器内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!
边栏推荐
- [quick start of Digital IC Verification] 6. Quick start of questasim (taking the design and verification of full adder as an example)
- Codeforces Round #804 (Div. 2) - A, B, C
- Welcome to the game and win rich bonuses: Code Golf Challenge officially launched
- Guidelines for application of Shenzhen green and low carbon industry support plan in 2023
- Scala基础【HelloWorld代码解析,变量和标识符】
- Informatics Olympiad 1338: [example 3-3] hospital setting | Luogu p1364 hospital setting
- PyTorch 1.12发布,正式支持苹果M1芯片GPU加速,修复众多Bug
- 计算lnx的一种方式
- 【数字IC验证快速入门】3、数字IC设计全流程介绍
- .Net分布式事務及落地解决方案
猜你喜欢

全国爱眼教育大会,2022第四届北京国际青少年眼健康产业展会

Zero cloud new UI design

B站UP搭建世界首个纯红石神经网络、基于深度学习动作识别的色情检测、陈天奇《机器学编译MLC》课程进展、AI前沿论文 | ShowMeAI资讯日报 #07.05

死信队列入门(两个消费者,一个生产者)

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

【数字IC验证快速入门】9、Verilog RTL设计必会的有限状态机(FSM)

Mysql频繁操作出现锁表问题

计算lnx的一种方式

小程序页面导航

Solve the problem that the database configuration information under the ThinkPHP framework application directory is still connected by default after modification
随机推荐
炒股开户最低佣金,低佣金开户去哪里手机上开户安全吗
IC科普文:ECO的那些事儿
Hong Kong stocks will welcome the "best ten yuan store". Can famous creative products break through through the IPO?
CTF逆向基础
小程序页面导航
PyTorch 1.12发布,正式支持苹果M1芯片GPU加速,修复众多Bug
How to form standard interface documents
信息学奥赛一本通 1339:【例3-4】求后序遍历 | 洛谷 P1827 [USACO3.4] 美国血统 American Heritage
Mongodb basic exercises
Applet page navigation
Leetcode brush questions: binary tree 18 (largest binary tree)
鸿蒙os第四次学习
[quick start of Digital IC Verification] 9. Finite state machine (FSM) necessary for Verilog RTL design
Y57. Chapter III kubernetes from entry to proficiency -- business image version upgrade and rollback (30)
【数字IC验证快速入门】7、验证岗位中必备的数字电路基础知识(含常见面试题)
July 4, 2022 - July 10, 2022 (UE4 video tutorial MySQL)
[Yugong series] go teaching course in July 2022 004 go code Notes
Is it safe for CICC fortune to open an account online?
Classic implementation method of Hongmeng system controlling LED
[quick start of Digital IC Verification] 7. Basic knowledge of digital circuits necessary for verification positions (including common interview questions)