1、配置信息
<!--redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
redis:
# redis 服务器地址
host: 127.0.0.1
# 端口
port: 6379
# 链接超时时间
timeout: 5000
jedis:
pool:
# 连接池最大连结数
max-active: 8
# 连接池最大阻塞时间
max-wait: 1
# 连接池中最大空闲链接
max-idle: 8
# 连接池中最小空闲链接
min-idle: 0
2、IDGeneratorUtil
package com.example.util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
public class IDGeneratorUtil {
private static StringRedisTemplate template = SpringUtil.getBean(StringRedisTemplate.class);
public static String getRedisNo(String pre, int length, boolean increment, boolean isDate) {
String date;
if (isDate) {
date = LocalDate.now().getYear() + "" + LocalDate.now().getMonthValue();
} else {
date = LocalDate.now().format(DateTimeFormatter.ISO_DATE).replace("-", "");
}
String key = pre + date;
String no;
if (increment) {
Long temp = template.opsForValue().increment(key, 1);
if (temp == 1) {
template.expire(key, isDate ? 30 : 1, TimeUnit.DAYS);
}
no = temp.toString();
} else {
no = template.opsForValue().get(key);
if (StringUtils.isEmpty(no)) {
no = Objects.requireNonNull(template.opsForValue().increment(key, 1)).toString();
template.expire(key, isDate ? 30 : 1, TimeUnit.DAYS);
}
}
if (no.length() >= length) {
return key + no;
} else {
StringBuilder temp = new StringBuilder();
for (int i = 0; i < length - no.length(); i++) {
temp.append("0");
}
return key + temp.toString() + no;
}
}
}