Redis 实现唯一全局ID

 

 

package com.hmdp.utils;

import org.springframework.beans.factory.annotation.Autowired;
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 RedisIdWorker {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    public static final Long BEGIN_TIMESTAMP=1672531200l; //2023-1-1 0.0.0
    public static final int COUNT_BITS=32;//move the bit count
    public  long nextId(String keyPrefix)
    {
        String fd= LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy:MM:dd")) ;//date key
        String incKey="inc:"+keyPrefix+":"+fd;
        //1 create time stamp
            LocalDateTime now=LocalDateTime.now();
            long second=now.toEpochSecond(ZoneOffset.UTC);
            long timestamp=second-BEGIN_TIMESTAMP;

        //2 create serial number

        Long count = stringRedisTemplate.opsForValue().increment(incKey);
        //3 union the timestamp with serial number and return

        return  timestamp<<COUNT_BITS | count;// move left COUNT_BITS then or calculator
    }

/*
    public static void main(String[] args) {
        LocalDateTime time=LocalDateTime.of(2023,1,1,0,0,0);
        long second=time.toEpochSecond(ZoneOffset.UTC);
        String fd= LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy:MM:dd")) ;
        System.out.println(fd);
    }*/
}

 

调用方法:

  @Resource
    private RedisIdWorker redisIdWorker;
    @Test
    public void IDTest()
    {
        for (int i = 0; i < 100; i++) {
            System.out.println(redisIdWorker.nextId("order"));
        }
        
    }

 

posted on 2023-03-03 11:04  hztech  阅读(82)  评论(0编辑  收藏  举报

导航