全局ID生成器,是一种在分布式系统下用来生产全局唯一ID的工具,一般要满足以下特性:
唯一性、高可用,高性能,递增性,安全性
Redis实现全局唯一ID:
@Component
public class RedisIdWorker {
private static final long BEGIN_TIMESTAMP = 1640996211L;
private static final short COUNT_BITS = 32;
private StringRedisTemplate stringRedisTemplate;
public long nextId(String keyPrefix){
//将参数作为前缀来区分业务
//1、生成时间戳
LocalDateTime now = LocalDateTime.now();
long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
long timestamp = nowSecond-BEGIN_TIMESTAMP;
//2、生产序列号
String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
long count = stringRedisTemplate.opsForValue().increment("icr:"+keyPrefix+":"+date);
//3、拼接返回
return timestamp<<COUNT_BITS | count;
}
}