使用Redis生成全局唯一ID示例

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

1.唯一性

2.高性能

3.安全性

4.递增性

5.高可用

复制代码
@Component
public class RedisIdWorker {
    /**
     * 定义一个开始的时间戳(秒级)
     * @param args
     */
    private static final long BEGIN_TIMESTAMP = 1640995200L;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    public long nextId(String keyPrefix){
        //1.生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowSecond - BEGIN_TIMESTAMP;
        //2.生成序列号
        String date = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        long count = redisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);//这里不会有有空指针
        //3.拼接并返回
        return timestamp << 32 | count;

    }

    public static void main(String[] args) {
        //获取从1970年1月1日0时0分0秒开始到2013.3.28日时间的秒数
        LocalDateTime time = LocalDateTime.of(2013, 3, 28, 0, 0, 0);
        long second = time.toEpochSecond(ZoneOffset.UTC);
        System.out.println("second:"+second);
    }
}

测试

复制代码
 @Autowired
    private RedisIdWorker redisIdWorker;

    private ExecutorService es = Executors.newFixedThreadPool(500);

    @Test
    public 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 = " + id);
            }
            latch.countDown();
        };
        long begin = System.currentTimeMillis();
        for (int i = 0; i < 300; i++) {
            es.submit(task);
        }
        
        long end = System.currentTimeMillis();
        System.out.println("time = " + (end - begin));
    }
相关推荐
咖啡の猫1 天前
Python字典的查询操作
数据库·python·c#
这儿有一堆花1 天前
2025 年免费指纹浏览器清单
数据库
我家领养了个白胖胖1 天前
SSE在Spring ai alibaba中同时使用Qwen和DeepSeek模型
java·后端·ai编程
AI科技摆渡1 天前
GPT-5.2介绍+ 三步对接教程
android·java·gpt
猿与禅1 天前
Spring Boot 4.0 完整核心特性及实践指南
java·spring boot·后端·spring·重大升级·springboot4.0
运维@小兵1 天前
Spring-AI系列——Tool Calling获取当前时间
java·后端·spring
认真敲代码的小火龙1 天前
【JAVA项目】基于JAVA的养老院管理系统
java·开发语言·课程设计
he___H1 天前
滑动窗口一题
java·数据结构·算法·滑动窗口
扶苏-su1 天前
Java---事件处理机制
java·开发语言
雨中飘荡的记忆1 天前
Hutool工具库实战
java