问题:订单id不能设置为自增长的原因
id的规律性太明显,
受订单的数据量限制:若数据量过大,需要多张表存储,若自增会导致id重复
全局ID生成器:在分布式系统中用来生成全局唯一ID的工具
ID的组成:
符号位:1bit ,默认为0
时间戳: 31bit 以秒为单位,可以使用约69年
序列号:32bit,秒内的计数量,
@Component
public class RedisIdWorker {@Resourceprivate StringRedisTemplate stringRedisTemplate;//redis全局ID生成器策略/**开始时间戳*/private static final long BEGIN_TIMESTAMP=1704067200L;/**序列号位数*/private static final int COUNT_BITS=32;public long nextId(String keyPrefix) {//1.生成时间戳LocalDateTime now = LocalDateTime.now();long nowSecond = now.toEpochSecond(ZoneOffset.UTC);long timestamp = nowSecond - BEGIN_TIMESTAMP;//2.生成序列号,使用redis的自增//2.1.获取当天日期,redis的key中使用“:”,分层级String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);//3.组装返回,使用位运算return (timestamp << COUNT_BITS) | count;}
}