吉安感知网项目-后端
linwei
2026-01-23 89bc9588e970964b0be8caa6ab259861faeeda0f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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;
    }
 
}