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自增
    • 雪花算法
    • 数据库自增 (单独一张自增表)
相关推荐
卧室小白14 小时前
Redis-哨兵模式
数据库·redis·缓存
GottdesKrieges14 小时前
OceanBase恢复常见问题
java·数据库·oceanbase
卧室小白14 小时前
redis-配置
数据库·redis·缓存
向風而行15 小时前
MySQL详解
数据库·mysql
belldeep16 小时前
本草纲目:如何应用 PostgreSQL 实现【中医药】主题数据库 ?
数据库·postgresql·本草纲目
Bert.Cai16 小时前
MySQL CURTIME()函数详解
数据库·mysql
Bert.Cai16 小时前
MySQL CURDATE()函数详解
数据库·mysql
NGSI vimp16 小时前
MySQL|MySQL 中 `DATE_FORMAT()` 函数的使用
数据库·mysql
HAWK eoni16 小时前
Mysql 驱动程序
数据库·mysql
二哈赛车手16 小时前
新人笔记---实现简易版的rag的bm25检索(利用ES),以及RAG上传时的ES与向量数据库双写
java·数据库·笔记·spring·elasticsearch·ai