全局Id生成器

为了增加id的安全性,我们可以不直接使用redis自增生成的数值,可以拼接一些其他的数值

redis全局锁 redis 全局id_java

id的组成部分

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

代码具体实现

点击查看代码

package com.waa.gulimall.order.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
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 RedisIdWoker {
@Autowired
private StringRedisTemplate stringRedisTemplate;
private static  final    long BEGIN_TIMESTAMP = 1674220484L;
private static  final  int COUNT_BIT = 32;
public long nextId(String keyPrefix){
    //1.生成时间戳
    final LocalDateTime localDateTime = LocalDateTime.now();
    final long nowTime = localDateTime.toEpochSecond(ZoneOffset.UTC);
    long timestamp = nowTime - BEGIN_TIMESTAMP;
    final String format = localDateTime.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
    //2.生成序列号
    final Long increment = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + format);
    return timestamp << COUNT_BIT | increment;
}

    public static void main(String[] args) {
        final LocalDateTime now = LocalDateTime.now();
        System.out.println(now.toEpochSecond(ZoneOffset.UTC));
    }

}