Redis实现全局唯一id

redis实现全局唯一id


java 复制代码
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdWorker {

    private StringRedisTemplate stringRedisTemplate;

    private static final long BEGIN_TIMESTAMP = 1640995200L;
    private static final int COUNT_BITS = 32;
    public RedisIdWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public long nextId(String keyPrefix){
        // 生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowSecond - BEGIN_TIMESTAMP;
        // 生成序列号
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);
        return timestamp << COUNT_BITS | count;
    }
}

timestamp << COUNT_BITS | count :

将timestamp 向左移动32位,再和count做或运算

  • 获取指定日期的时间戳
java 复制代码
	@Test
    void test() throws Exception{
        LocalDateTime dateTime = LocalDateTime.of(2022, 1, 1, 0, 0, 0);
        long epochSecond = dateTime.toEpochSecond(ZoneOffset.UTC);
        System.out.println("epochSecond = " + epochSecond);
    }
  • 其他全局ID生成策略
    • UUID
    • redis自增
    • 雪花算法
    • 数据库自增 (单独一张自增表)
相关推荐
浠寒AI18 分钟前
PostgreSQL 与 SQL 基础:为 Fast API 打下数据基础
数据库·sql·postgresql
金州饿霸20 分钟前
MySQL--慢查询日志、日志分析工具mysqldumpslow
数据库·mysql
zhujilisa23 分钟前
MySql中的锁
数据库·mysql
百度Geek说1 小时前
BaikalDB 架构演进实录:打造融合向量化与 MPP 的 HTAP 查询引擎
数据库·分布式·架构
Xy9102 小时前
App Trace技术解析:传参安装、一键拉起与快速安装
数据库·程序员
朝九晚五ฺ2 小时前
【MySQL基础】MySQL表操作全面指南:从创建到管理的深度解析
数据库·sql
whltaoin2 小时前
Redis专题-实战篇一-基于Session和Redis实现登录业务
redis·缓存·springboot
AIGC_北苏2 小时前
Ubuntu 安装 Mysql 数据库
数据库·mysql·ubuntu
15942315633 小时前
QT使用WxSQLite3打开加密数据库并查询
数据库·qt·sqlite