分布式订单编号
1、案例分析
系统需要生成根据业务类型生成流水号,每天从0开始生成,第二天会清零继续从0开始
流水号格式: bizCode + date + incr
如:KS-20171123 -000000、 KS-20171123 -000001、KS-20171123 -000002……
如:KS-20171124 -000000、 KS-20171124 -000001、KS-20171124 -000002……
好处:可以根据订单编号里面得知今天有多少个订单信息
2、具体实现
- 利用Redis Incr 生成序列号,使用日期加业务编码作为组合Key,保证第二天生成的序列号又是从0开始。
- 由于业务量不是很大,在生成序列号之前先判断一下当前key是否存在,若不存在,设置此key过期时间为当天晚上23:59:59,避免生成很多过期key。
难点1:补零操作
难点2:过了当天就清零重新累加
原理:redis中的expire命令,进行key的过期设置。
# 解决方案
127.0.0.1:6379> set product:id 1
OK
127.0.0.1:6379> expire product:id 100
(integer) 1
2.1 redis生成唯一序号
package com.example.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
@Component
public class CacheService {
@Autowired
private RedisTemplate redisTemplate;
/**
* @Auther: 长颈鹿
* @Date: 2021/08/11/15:11
* @Description:
* @Param: [key]
* @return: java.lang.Long
*
* key传进来的含义:可以为不同的业务生成对应的流水号
* 1:key--product :createor
* 2:key--order:createor
**/
public Long getIncrementNum(String key) {
// redis的incr计数器,从0开始
RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
// 计数器累加,步长+1
Long counter = entityIdCounter.incrementAndGet();
// 初始设置过期时间,过了当天就清零重新累加
if ((null == counter || counter.longValue() == 1)) {
System.out.println("设置过期时间为1天!");