优秀的编程知识分享平台

网站首页 > 技术文章 正文

系统开发中的唯一流水号生成——Redis

nanyue 2025-03-28 19:30:27 技术文章 6 ℃

一、前言

无论做什么类型的系统,都会牵涉到一个唯一流水号生成的问题,这个流水号可能是不规则的,也可能是有特定的有序格式。

在系统开发中比较常用的有数据库生成、缓存生成、数据库+缓存。这里就上述情况做一些简要记录。

二、数据库生成

之前有使用过的一种方案:同步锁 + MySql。在一张数据表中记录最新的流水号数据,然后通过SQL获取数据并做 +1 处理。

这里需要注意一些问题:

① 并发问题

② 唯一的索引确保数据不重复

三、缓存(Redis)生成

在Redis中有一个类叫做:RedisAtomicLong可以比较好的解决这个问题。

我们在IDE中点进去这部分的源码可以看到它的一些操作:

① 固定步长为1

② volatile修饰Key,内存共享

③ 先增加再获取数据

④ 单线程操作(PS:什么?Redis6.0多线程...)





四、关键代码如下


    /**
     * 功能描述: 生成流水
     * Param: [] 
     * Return: java.lang.String
     */
    private String generateAutoId(){
        RedisConnectionFactory connectionFactory = stringRedisTemplate.getConnectionFactory();
        if (connectionFactory == null) {
            throw new RuntimeException("RedisConnectionFactory is required !");
        }
        RedisAtomicLong atomicLong = new RedisAtomicLong("autoId:autoId", connectionFactory);
        /* 设置过期时间 */
        LocalDate now = LocalDate.now();
        LocalDateTime expire = now.plusDays(1).atStartOfDay();
        atomicLong.expireAt(Date.from(expire.atZone(ZoneId.systemDefault()).toInstant()));
        Long autoID = atomicLong.getAndIncrement();
        DecimalFormat df = new DecimalFormat("00000");
        /* 流水号不足5位补充成5位 */
        String autoNumber = df.format(autoID);
        System.out.println(autoNumber);
        return autoNumber;
    }



同时做简要测试:

    @Test
    void contextLoads() {

        List threads = new ArrayList<>();
        for (int i = 0; i < 1000 i thread thread='new' threadthis::generateautoid threads.addthread threads.foreachthread::start threads.foreachx -> {
            try {
                x.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

    }



测试结果:



五、后记

① 使用数据库+同步锁生成代码简单但效率稍微低,适合访问量较少的系统。

② 使用缓存生成代码同样简介,由于Redis的特性(单线程、存放于内存)能满足高并发,但是数据可能丢失。

③ 数据库 + 缓存(适用于大部分分布式高并发系统)其大致操作流程如下



最近发表
标签列表