(笔记总结自《黑马点评》项目)
全局ID生成器,是一种在分布式系统下用来生成全局唯一ID的工具,一般要满足下列特性:
为了增加ID的安全性,我们可以不直接使用Redis自增的数值,而是拼接一些其它信息:
ID的组成部分:
符号位:永远为0。
时间戳:31bit,以秒为单位,可以使用69年。
序列号:32bit,秒内的计数器,支持每秒产生2^32个不同ID。
ID生成器代码:
- @Component
- public class RedisIdWorker {
-
- //开始时间戳
- private static final long BEGIN_TIMESTAMP = 1640995200L;
-
- @Resource
- private 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("yyyyMMdd"));
- Long count = stringRedisTemplate.opsForValue().increment("icr:" + KeyPrefix + ":" + date);
- //拼接并返回
- //位运算,时间戳向左移动32位,右边空出的0用序列号补充,可以用或运算填充
- return timestamp << 32 | count;
- }
-
- public static void main(String[] args) {
- LocalDateTime time = LocalDateTime.of(2022, 1, 1, 0, 0, 0);
- long second = time.toEpochSecond(ZoneOffset.UTC);
- System.out.println(second);
- }
- }
测试代码:
- @Resource
- private RedisIdWorker redisIdWorker;
-
- private ExecutorService es = Executors.newFixedThreadPool(500);
- @Test
- void testIdWorker() throws InterruptedException {
- CountDownLatch latch = new CountDownLatch(300);
- Runnable task = () ->{
- for(int i = 0; i<100 ;i++){
- long id = redisIdWorker.nextId("order");
- System.out.println(id);
- }
- latch.countDown();
- };
- long begin = System.currentTimeMillis();
- for (int i = 0; i<300 ;i++){
- es.submit(task);
- }
- latch.await();
- long end = System.currentTimeMillis();
- System.out.println(end - begin);
- }