package org.sxkj.common.utils;
|
|
import cn.hutool.core.date.DateUtil;
|
import org.sxkj.common.constant.CacheConstant;
|
import org.sxkj.common.constant.CommonConstant;
|
import org.sxkj.common.redis.RedisOpsUtils;
|
|
import java.util.Date;
|
import java.util.Objects;
|
import java.util.Optional;
|
import java.util.concurrent.TimeUnit;
|
|
public class OrderNumUtils {
|
|
/**
|
* 工单编号生成 最后几位格式化
|
*
|
* @param num 当前编号数
|
* @param minLength 最小后缀长度 默认3
|
* @return 格式化后编号
|
*/
|
private static String formatDayOrderNumLast(Integer minLength, Integer num) {
|
int maxLength = Math.max(Optional.ofNullable(minLength).orElse(3),
|
num.toString().length());
|
return String.format("%0" + maxLength + "d", num);
|
}
|
|
/**
|
* 获取redis中订单自增id 数
|
*
|
* @param prefKey 前缀key值
|
* @return
|
*/
|
private static Integer getRedisNumValue(String prefKey) {
|
Date date = new Date();
|
String currentTime = DateUtil.format(date, CommonConstant.yyyyMMdd);
|
String redisKey = CacheConstant.ORDER_NUM_KEY + prefKey + ":" + currentTime;
|
Object numResult = RedisOpsUtils.get(redisKey);
|
if (Objects.isNull(numResult)) {
|
RedisOpsUtils.setWithExpire(redisKey, 1L, TimeUnit.DAYS.toSeconds(1));
|
return 0;
|
} else {
|
RedisOpsUtils.increment(redisKey, 1L);
|
}
|
if (numResult instanceof Integer) {
|
return (Integer) numResult;
|
} else if (numResult instanceof Long) {
|
return ((Long) numResult).intValue();
|
}
|
return 0;
|
}
|
|
/**
|
* 订单号生成
|
*
|
* @param prefKey 缓存前缀key
|
* @return 订单号生成
|
*/
|
public static String initOrderNum(String prefKey) {
|
Integer num = getRedisNumValue(prefKey);
|
String lastNum = formatDayOrderNumLast(3, num + 1);
|
Date date = new Date();
|
String currentTime = DateUtil.format(date, CommonConstant.yyyyMMddHHmmss);
|
return currentTime + lastNum;
|
}
|
|
}
|