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自增
    • 雪花算法
    • 数据库自增 (单独一张自增表)
相关推荐
瀚高PG实验室1 小时前
发布端逻辑复制槽消失
数据库·postgresql·瀚高数据库
ss2731 小时前
PostgreSQL慢查询定位与优化
数据库·postgresql
香蕉大香蕉(06敬畏市场)1 小时前
MySQL 单点详解(07)
java·数据库·mysql·ai·博客·八股
smilejingwei3 小时前
TRAE 插件上新 | SQLazy:让 AI 写出可信复杂 SQL
数据库·人工智能·sql
我要见SA姐13 小时前
GitHub Actions 自动化:5 个真实运维提效案例
运维·数据库·机器学习·oracle·回归
QXWZ_IA4 小时前
边坡监测预算有限时的建设顺序:虚拟基准站与成本账
网络·数据库
这个DBA有点耶4 小时前
1亿条向量内存降95.4%,延迟降80%:金仓AI原生内核真能解决RAG痛点?
数据库·人工智能·开源
Y3815326624 小时前
用 httpx 写 SerpBase 异步客户端:连接池与超时配置
运维·服务器·数据库
c_hn_0075 小时前
量化数据12:国内期货L2历史数据:Tick、逐笔、五档盘口一次性打包下载
数据库·1024程序员节·#深度订单簿数据·#历史行情订单薄·#本地csv数据存储
GeW5 小时前
从"补短板"到"强优势"Linux与数据库认证成为产业跃迁人才支点
linux·数据库