记Redis生成流水单号解决方案

2020-10-06 04:07:44  晓掌柜  版权声明:本文为站长原创文章,转载请写明出处


一、前言


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

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


二、数据库生成


    之前有使用过的一种方案:同步锁 + 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<Thread> threads = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
Thread thread = new Thread(this::generateAutoId);
threads.add(thread);
}

threads.forEach(Thread::start);
threads.forEach(x -> {
try {
x.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
});

}


    测试结果:    

    

    


五、后记


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

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

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


    





更多精彩请关注guangmuhua.com


最新评论:

2021-06-02 17:32:32
1楼
66666666666666666
2020-10-27 09:45:18
2楼