今天介绍个基于redis实现自增流水号的一个案例
为什么使用redis来实现自增流水号呢?
因为现在的项目很多都整合redis,而且redis是单线程,且基于内存操作,速度快,实现自增流水号代码也简单
小编实现的方式是Vue+springBoot,但是Vue就是做个页面按钮为了测试,你们可以写个测试类来测试,现在放上后端代码,亲测有效!!!
首先先引入依赖,在pom文件加
org.springframework.boot spring-boot-starter-data-redis org.springframework.boot spring-boot-starter-test test com.alibaba fastjson
创建一个实体,便于操作,也可以不创建随意
import lombok.Data;
@Data
public class GenCode {
// 流水号生成依赖的类,会使用类的名称作为redis的key
private String name;
// 前缀
private String prefix;
// 自增数位数 自增数达不到此位数自动补零
private Integer num;
public GenCode(String name, String prefix, Integer num) {
this.name = name;
this.prefix = prefix;
this.num = num;
}
}
创建两个Util工具类,一个是redis实现流水号自增,另一个是fastJson转换
FastJsonUtils.java
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import java.util.List;
import java.util.Map;
public class FastJsonUtils {
public static T getJsonToBean(String jsonData, Class clazz) {
return JSON.parseObject(jsonData, clazz);
}
public static String getBeanToJson(Object object) {
return JSON.toJSONString(object);
}
public static List getJsonToList(String jsonData, Class clazz) {
return JSON.parseArray(jsonData, clazz);
}
public static List
RedisUtil.java
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Optional;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@Component
@Slf4j
public class RedisUtil {
@Autowired
StringRedisTemplate stringRedisTemplate;
public Optional gen() {
// 获取实体类的名称
String redisKey = "流水号测试";
// 判断是不是有初始化此实体类
if (null != stringRedisTemplate.opsForValue().get(redisKey)) {
// 从缓存获取流水号的生成信息
GenCode GenCode = FastJsonUtils.getJsonToBean(stringRedisTemplate.opsForValue().get(redisKey).toString(), GenCode.class);
// 根据流水号的前缀判断今天是否有生成过流水号
if (stringRedisTemplate.opsForValue().get(GenCode.getPrefix()) == null) {
// 没有则新建一个存入缓存 格式(key:OR value:0)
// 设置到第二天早上00:00:01过期
Long todayTime = LocalDate.now().plusDays(1).atTime(0, 0, 0, 1).atOffset(ZoneOffset.ofHours(8)).toEpochSecond();
Long nowTime = LocalDateTime.now().atOffset(ZoneOffset.ofHours(8)).toEpochSecond();
Long expireTime = todayTime - nowTime;
stringRedisTemplate.opsForValue().set(GenCode.getPrefix(), String.valueOf(0), expireTime*1000, TimeUnit.MILLISECONDS);
}
// 进行自增操作
StringBuffer sn = new StringBuffer();
// 和前缀、时间、随机数进行组合
sn.append(GenCode.getPrefix());
String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
sn.append(date);
//流水号自动自增
Long num = stringRedisTemplate.opsForValue().increment(GenCode.getPrefix());
sn.append(addZero(String.valueOf(num), GenCode.getNum()));
//介于0-1000之前生成随机数
// String random = String.valueOf(new Random().nextInt(1000));
// sn.append(random);
// 生成最终的流水号返回
log.info("=====重新生成流水号" + sn.toString() + "开始=====");
stringRedisTemplate.opsForValue().set(redisKey, sn.toString());
log.info("=====重新生成流水号" + sn.toString() + "完毕=====");
//java8判断是否是null
return Optional.ofNullable(sn.toString());
}
return Optional.ofNullable(null);
}
// 自动补零
public String addZero(String numStr, Integer maxNum) {
int addNum = maxNum - numStr.length();
StringBuffer rStr = new StringBuffer();
for (int i = 0; i < addNum; i++) {
rStr.append("0");
}
rStr.append(numStr);
return rStr.toString();
}
}
现在来写controller层的具体调用操作
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
@RestController
@Slf4j
@RequestMapping("/redisTest")
public class RedisTestController {
@Autowired
StringRedisTemplate stringRedisTemplate;
@Resource
RedisUtil redisUtil;
@PostMapping("/getNumber")
public void test() throws Exception {
log.info("=====开始初始化流水号=====");
List GenCodeList = new ArrayList<>();
GenCodeList.add(new GenCode("流水号测试", "自增号", 6));
init(GenCodeList);
redisUtil.gen();
log.info("=====初始化流水号完毕=====");
}
public void init(List GenCodes) {
// 流水号初始化入缓存
for (GenCode GenCode : GenCodes) {
String redisKey = GenCode.getName();
// 存入缓存 key:key:实体类名称 value:流水号数据(前缀、自增数位数)
stringRedisTemplate.opsForValue().set(redisKey, FastJsonUtils.getBeanToJson(GenCode));
log.info(GenCode.getName() + "已初始化");
}
}
}
其实redis工具类可以不用写,也可以直接创建数据,但是我前面的操作就是为了测试redis能否存入,redisTemplate是否为空
结果,测试自增



