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自增
    • 雪花算法
    • 数据库自增 (单独一张自增表)
相关推荐
nVisual6 小时前
巡检任务与工单闭环方案
运维·服务器·数据库·数据中心基础设施
承渊政道6 小时前
从设备数据到AI洞察:时序数据的多模融合实践
数据库·人工智能·性能优化·金仓数据库·多模融合
科技圈快迅6 小时前
2026年数据库国产化替代性能调优方法论:从SQL基线建立到持续优化的全流程体系
数据库·sql
你有我备注吗6 小时前
SQL之数据更新
数据库·sql
跨境技工小黎6 小时前
动态住宅代理使用指南:粘性会话 vs. 每次请求轮换 IP,如何选择?
数据库
AAA@峥7 小时前
系统化学习 MySQL:数据类型、库表管理、增删改查全解析
数据库·学习·mysql
流星白龙15 小时前
【Redis】2.Redis重大版本
数据库·redis·junit
流星白龙15 小时前
【Redis】7.Hash表
数据库·redis·哈希算法
流星白龙16 小时前
【Redis】4.基本全局命令
数据库·redis·缓存
王八八。16 小时前
Navicat 17破解版下载安装教程 附安装激活步骤(2026 最新版)
数据库·navicat