车间能级提升-智能设备管理系统
朱桂飞
2025-02-12 3f476e9dc149c89df5fff1513a690ff05ec545c9
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
package org.dromara.eims.controller;
 
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.constant.CacheConstants;
import org.dromara.common.core.domain.R;
import org.dromara.common.redis.utils.RedisUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
 
 
/**
 * 【生成编码】
 *
 * @author zhuguifei
 * @date 2025-02-11
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/eims/generate")
public class GenerateCodeController {
    /**
     * 根据前缀生成各种编码
     *
     * @param prefix 前缀
     * @return
     */
    @GetMapping("/{prefix}")
    public R<String> generateCode(@NotNull(message = "类型不能为空")
                                      @PathVariable String prefix) {
        String todayStr = DateTimeFormatter.ofPattern("yyyyMMdd").format(LocalDate.now());
        String key = CacheConstants.EIMS_GENERATE_CODE + ":" + prefix;
        String code;
        // 使用Redis的原子性操作避免并发问题
        String oldCode = RedisUtils.getCacheObject(key);
        if (oldCode != null && oldCode.contains(todayStr)) {
            int no = Integer.parseInt(oldCode.substring(oldCode.length() - 4));
            code = String.format("%s%s%04d", prefix, todayStr, no + 1);
        } else {
            code = String.format("%s%s%04d", prefix, todayStr, 1);
        }
        // 更新缓存
        try {
            RedisUtils.setCacheObject(key, code);
        } catch (Exception e) {
            return R.fail("生成编码失败,请稍后重试!");
        }
 
        return R.ok("生成成功!", code);
 
    }
}