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);
    }
相关推荐
叶子椰汁17 分钟前
ORMPP链接MySQL 8.0错误
服务器·数据库·c++·mysql
电商数据girl26 分钟前
【经验分享】浅谈京东商品SKU接口的技术实现原理
java·开发语言·前端·数据库·经验分享·eclipse·json
老兵发新帖43 分钟前
AWS RDS :多引擎托管数据库服务
数据库·云计算·aws
liyongjie1 小时前
openEuler安装BenchmarkSQL
数据库
咚咚咚小柒1 小时前
SQL基础知识,MySQL学习(长期更新)
数据库·sql·mysql·database
四四夕夕3 小时前
【保姆级图文】1panel 面板部署雷池社区版:从环境搭建到安全验证全流程实录
数据库·安全
仍然探索未知中3 小时前
MySQL数据库介绍以及安装(本地windows、Ubuntu 20.04)
数据库·mysql
m0_653031364 小时前
腾讯云TCCA认证考试报名 - TDSQL数据库交付运维工程师(PostgreSQL版)
运维·数据库·腾讯云
朱小勇本勇4 小时前
Clang Code Model: Error: The clangbackend executable “D:\Soft\Qt5.12.12\Tool
运维·服务器·数据库·qt·nginx
代码的余温4 小时前
B树与B+树:数据库索引背后的秘密
数据结构·数据库·b树