Redis 原子性生成序号/流水号/顺序值
直接贴代码
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48package com.example.demo1.redis; import cn.hutool.core.date.DateUtil; import org.redisson.api.RAtomicLong; import org.redisson.api.RedissonClient; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.util.Date; @Component public class OrderSnUtil { @Resource private RedissonClient redissonClient; /** * 获取订单编号 * * @return 订单编号 */ public String getOrderSn() { // 时间戳随机数 String time = DateUtil.format(new Date(), "yyMMddHHmmss"); int random = (int) ((Math.random() * 9 + 1) * 100); //设置key值 key值不同从头计算 RAtomicLong atomicLong = redissonClient.getAtomicLong("order_num"); long orderNum; if (!atomicLong.isExists()) { orderNum = atomicLong.incrementAndGet(); //设置失效时间 Date endOfDay = DateUtil.offsetHour(new Date(),1); atomicLong.expireAt(endOfDay); } else { orderNum = atomicLong.incrementAndGet(); } StringBuilder no = new StringBuilder(String.valueOf(orderNum)); //设置长度 if (no.length() > OrderSnPrefix.ORDER_SN_LENGTH) { atomicLong.delete(); orderNum = atomicLong.incrementAndGet(); Date endOfDay = DateUtil.offsetHour(new Date(),1); atomicLong.expireAt(endOfDay); } no = new StringBuilder(String.valueOf(orderNum)); //自动补0 while (no.length() < OrderSnPrefix.ORDER_SN_LENGTH) { no.insert(0, "0"); } return OrderSnPrefix.ORDER + time + random + no; } }
最后
以上就是迷路河马最近收集整理的关于Redis 原子性生成序号/流水号/顺序值的全部内容,更多相关Redis内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复