使用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));
    }
相关推荐
金銀銅鐵3 小时前
带您看懂字节码指令(一):一帧里有什么
java·后端·ai编程
nice_lcj5205 小时前
【从零理解 Spring AI · 14】RAG 的四个环节:加载、切分、向量化、检索
java·spring boot·embedding·向量数据库·rag·spring ai·ai应用开发
学长毕设7 小时前
基于springboot科创竞赛信息平台-附源码
java·spring boot·后端
聪明的笨猪猪7 小时前
Java 工程案例:AI 生成 @Async 异步线程池踩坑
java·经验分享·面试·ai编程
学长毕设8 小时前
基于SpringBoot公务员考试交流平台-附源码
java·spring boot·后端
SelectDB8 小时前
让变更流出 Doris:Apache Doris 5.0 基于增量计算的 CDC 技术解析
数据库
这个DBA有点耶8 小时前
MCP隔离层+行级语义审计+输出校验:AI访问数据库的安全边界拆解
数据库·人工智能·ai编程
这个DBA有点耶9 小时前
从反向扫描O(n)到正向扫描O(1):降序索引的物理机制与混合排序匹配规则
数据库
码哥字节10 小时前
缓存一致性:先删缓存还是先更新库?3 种方案对比 + 实战
redis