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);
    }
相关推荐
2501_941148151 小时前
多语言微服务架构与边缘计算技术实践:Python、Java、C++、Go深度解析
数据库
w***z502 小时前
MYSQL 创建索引
数据库·mysql
章鱼哥7303 小时前
[特殊字符] SpringBoot 自定义系统健康检测:数据库、Redis、表统计、更新时长、系统性能全链路监控
java·数据库·redis
5***E6853 小时前
MySQL:drop、delete与truncate区别
数据库·mysql
记得记得就1513 小时前
【MySQL数据库管理】
数据库·mysql·oracle
Austindatabases4 小时前
给PG鸡蛋里面挑骨头--杭州PostgreSQL生态大会
数据库·postgresql
秃了也弱了。4 小时前
MySQL空间函数详解,MySQL记录经纬度并进行计算
android·数据库·mysql
星环处相逢4 小时前
MySQL数据库管理从入门到精通:全流程实操指南
数据库·mysql
h***04774 小时前
SpringBoot集成Flink-CDC,实现对数据库数据的监听
数据库·spring boot·flink
源来猿往4 小时前
redis-架构解析
数据库·redis·缓存