今天介绍个基于redis实现自增流水号的一个案例 为什么使用redis来实现自增流水号呢? 因为现在的项目很多都整合redis,而且redis是单线程,且基于内存操作,速度快,实现自增流水号代码也简单
小编实现的方式是Vue+springBoot,但是Vue就是做个页面按钮为了测试,你们可以写个测试类来测试,现在放上后端代码,亲测有效!!!
首先先引入依赖,在pom文件加
<!--redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- 测试 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
创建一个实体,便于操作,也可以不创建随意
import lombok.Data;
@Data
public class GenCode {
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> T getJsonToBean(String jsonData, Class<T> clazz) {
return JSON.parseObject(jsonData, clazz);
}
public static String getBeanToJson(Object object) {
return JSON.toJSONString(object);
}
public static <T> List<T> getJsonToList(String jsonData, Class<T> clazz) {
return JSON.parseArray(jsonData, clazz);
}
public static List<Map<String, Object>> getJsonToListMap(String jsonData) {
return JSON.parseObject(jsonData, new TypeReference<List<Map<String, Object>>>() {
});
}
public static <T> String listToJson(List<T> ts) {
String jsons = JSON.toJSONString(ts);
return jsons;
}
public static <T> T getObjectToClass(Object object, Class<T> tClass) {
String json = getBeanToJson(object);
return getJsonToBean(json, tClass);
}
public static <T> List<T> jsonToList(String jsonString, Class<T> clazz) {
@SuppressWarnings("unchecked")
List<T> ts = JSONArray.parseArray(jsonString, clazz);
return ts;
}
}
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<String> 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) {
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()));
log.info("=====重新生成流水号" + sn.toString() + "开始=====");
stringRedisTemplate.opsForValue().set(redisKey, sn.toString());
log.info("=====重新生成流水号" + sn.toString() + "完毕=====");
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<GenCode> GenCodeList = new ArrayList<>();
GenCodeList.add(new GenCode("流水号测试", "自增号", 6));
init(GenCodeList);
redisUtil.gen();
log.info("=====初始化流水号完毕=====");
}
public void init(List<GenCode> GenCodes) {
for (GenCode GenCode : GenCodes) {
String redisKey = GenCode.getName();
stringRedisTemplate.opsForValue().set(redisKey, FastJsonUtils.getBeanToJson(GenCode));
log.info(GenCode.getName() + "已初始化");
}
}
}
其实redis工具类可以不用写,也可以直接创建数据,但是我前面的操作就是为了测试redis能否存入,redisTemplate是否为空
结果,测试自增
|