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自增
    • 雪花算法
    • 数据库自增 (单独一张自增表)
相关推荐
一只小bit2 小时前
MySQL事务:如何保证ACID?MVCC到底如何工作?
数据库·mysql·oracle
小猪咪piggy2 小时前
【项目】小型支付商城 MVC/DDD
java·jvm·数据库
向阳而生,一路生花2 小时前
redis离线安装
java·数据库·redis
·云扬·2 小时前
使用pt-archiver实现MySQL数据归档与清理的完整实践
数据库·mysql
黄焖鸡能干四碗2 小时前
信息安全管理制度(Word)
大数据·数据库·人工智能·智慧城市·规格说明书
zhangyifang_0092 小时前
PostgreSQL一些概念特性
数据库·postgresql
weixin_46682 小时前
安装Zabbix7
数据库·mysql·zabbix
数据库生产实战2 小时前
Oracle 19C实测:重命名分区表后又重命名分区索引,分区索引会失效吗?DBA必看避坑指南!
数据库·oracle·dba
king_harry2 小时前
window server2008下Oracle 配置dblink查询 MySQL 数据
数据库·mysql·oracle·odbc·dblink
chde2Wang2 小时前
hbase启动报错-keeperErrorCode
大数据·数据库·hbase