zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

Redis生成全局唯一ID的实现方法

Redis方法 实现 生成 ID 唯一 全局
2023-06-13 09:19:48 时间
生成规则:

有时为了增加ID的安全性,我们可以不直接使用Redis自增的数值,而是拼接一些其他信息

ID组成部分:

符号位:1bit,永远为0 时间戳:31bit,以秒为单位,可以使用69年 序列号:32bit,秒内的计数器,支持每秒产生2^32个不同ID

 ID生成类: package com.example.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @Author DaBai
 * @Date 2022/3/17 下午 09:25
 * @Version 1.0
 */

@Component
public class RedisIDWorker {
    private static final long BEGIN_TIMESTAMP = 1640995200L;

    /**
     * 序列号位数
     */
    private static final int COUNT_BITS = 32;

    private StringRedisTemplate stringRedisTemplate;

    public RedisIDWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public long nextID(String keyPrefix) {
        //1、生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowScond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowScond BEGIN_TIMESTAMP;
        //2、生成序列号
        // 2.1 获取当前日期,精确到天
        String date = now.format(DateTimeFormatter.ofPattern( yyyy:MM:dd ));
        long count = stringRedisTemplate.opsForValue().increment( icr + keyPrefix + : + date);

        //3、拼接字符串
        // 时间戳左移32位,然后 或 序列号,有1为1
        long ids = timestamp COUNT_BITS | count;
        return ids;
    }

@Resource
    RedisIDWorker redisIDWorker;

    private ExecutorService es = Executors.newFixedThreadPool(500);

    @Test
    public void ShowID() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(300);
        Runnable task = () - {
            for (int i = 0; i 100; i++) {
                long id = redisIDWorker.nextID( order );
                System.out.println( id = + id);
            }
            countDownLatch.countDown();
        };
        long startTime = System.currentTimeMillis();
        for (int i = 0; i 300; i++) {
            es.submit(task);
        }
        countDownLatch.await();
        long end = System.currentTimeMillis();
        System.out.println( time = + (end startTime));
    }

到此这篇关于Redis生成全局唯一ID的实现方法的文章就介绍到这了,更多相关Redis生成全局唯一ID内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!


我想要获取技术服务或软件
服务范围:MySQL、ORACLE、SQLSERVER、MongoDB、PostgreSQL 、程序问题
服务方式:远程服务、电话支持、现场服务,沟通指定方式服务
技术标签:数据恢复、安装配置、数据迁移、集群容灾、异常处理、其它问题

本站部分文章参考或来源于网络,如有侵权请联系站长。
数据库远程运维 Redis生成全局唯一ID的实现方法