Redis:实现全局唯一id

(笔记总结自《黑马点评》项目)

一、全局ID生成器

全局ID生成器,是一种在分布式系统下用来生成全局唯一ID的工具,一般要满足下列特性:

二、原理

为了增加ID的安全性,我们可以不直接使用Redis自增的数值,而是拼接一些其它信息:

ID的组成部分:

符号位:永远为0。

时间戳:31bit,以秒为单位,可以使用69年。

序列号:32bit,秒内的计数器,支持每秒产生2^32个不同ID。

三、样例代码

ID生成器代码:

java 复制代码
@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);
    }
}

测试代码:

java 复制代码
    @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);
    }
相关推荐
光影少年10 分钟前
postgrsql和mysql区别?
数据库·mysql·postgresql
Arva .13 分钟前
说说Redis的单线程架构
redis
pingcode26 分钟前
IDEA清除缓存
缓存·intellij-idea
Hello.Reader33 分钟前
Flink SQL Window Top-N窗口榜单的正确打开方式
数据库·sql·flink
wsx_iot36 分钟前
MySQL 的 MVCC(多版本并发控制)详解
数据库·mysql
Shingmc338 分钟前
MySQL表的增删改查
数据库·mysql
敲上瘾41 分钟前
MySQL主从集群解析:从原理到Docker实战部署
android·数据库·分布式·mysql·docker·数据库架构
电子_咸鱼42 分钟前
【QT——信号和槽(1)】
linux·c语言·开发语言·数据库·c++·git·qt
pandarking43 分钟前
[CTF]攻防世界:web-unfinish(sql二次注入)
前端·数据库·sql·web安全·ctf
程序猿20231 小时前
MySQL索引性能分析
数据库·mysql