使用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));
    }
相关推荐
Hadoop_Liang1 分钟前
解决Mawell1.29.2启动SQLException: You have an error in your SQL syntax问题
大数据·数据库·maxwell
oneDay++14 分钟前
# IntelliJ IDEA企业版高效配置指南:从主题到快捷键的终极优化
java·经验分享·intellij-idea·学习方法
Jasmin Tin Wei22 分钟前
idea中的vcs不见了,如何解决
java·ide·intellij-idea
码上飞扬31 分钟前
MongoDB数据库深度解析:架构、特性与应用场景
数据库·mongodb·架构
飞天红猪侠c43 分钟前
MySQL-逻辑架构
数据库·mysql
Java程序员-小白1 小时前
使用java -jar命令指定VM参数-D运行jar包报错问题
java·开发语言·jar
文牧之1 小时前
AutoVACUUM (PostgreSQL) 与 DBMS_STATS.GATHER_DATABASE_STATS_JOB_PROC (Oracle) 对比
运维·数据库·postgresql·oracle
ClearViper32 小时前
Java的多线程笔记
java·开发语言·笔记
{⌐■_■}2 小时前
【redis】redis常见数据结构及其底层,redis单线程读写效率高于多线程的理解,
数据结构·数据库·redis
全栈凯哥2 小时前
Java详解LeetCode 热题 100(17):LeetCode 41. 缺失的第一个正数(First Missing Positive)详解
java·算法·leetcode