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);
|
|
}
|
}
|