【Redis 开发】全局ID生成器

发布于:2024-04-27 ⋅ 阅读:(22) ⋅ 点赞:(0)

全局ID生成器

为了增加ID的安全性,我们可以不直接使用Redis自增的数值,而是拼接一些其他信息:
在这里插入图片描述
ID的组成部分:

符号位:1bit,一直为0
时间戳:31bit,一秒为单位,可以使用69年
序列号:32bit,秒内的计数器,支持每秒生成2^32个不同的ID

通俗的来讲就是将我们这里的Redis中的key使用全局ID生成器来进行代替,所以需要生成ID生成器:

@Component
public class RedisIdWorker {
    /**
     * 开始的时间戳
     */
    private static final long BEGIN_TIMESTAMP=1704067200L;
    private static final  int COUNT_BITS =32;

    public RedisIdWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    private StringRedisTemplate stringRedisTemplate;
    public long nextId(String Keyprefix){
        //1.生成时间戳
        LocalDateTime time=LocalDateTime.now();
        long epochSecond = time.toEpochSecond(ZoneOffset.UTC);
        long timestamp = epochSecond - BEGIN_TIMESTAMP;
        //2.生成序列号
        //获取当前日期,精确到天
        String date = time.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        //自增张
        Long increment = stringRedisTemplate.opsForValue().increment("hlh:" + Keyprefix + ":" + date);
        //3.拼接并返回
        return timestamp<<COUNT_BITS| increment;
    }

    public static void main(String[] args) {
        LocalDateTime time =LocalDateTime.of(2024,1,1,0,0,0);
        long epochSecond = time.toEpochSecond(ZoneOffset.UTC);
        System.out.println("second="+epochSecond);
    }
}

网站公告

今日签到

点亮在社区的每一天
去签到