feat: 生成任务编码工具类

This commit is contained in:
Kelvin 2024-11-02 09:41:08 +08:00
parent 4e2e07cfa4
commit eaa4196c58
3 changed files with 87 additions and 0 deletions

View File

@ -5,6 +5,8 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import com.ktg.generator.util.MultiModuleCodeGenerator;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
@ -211,4 +213,10 @@ public class GenController extends BaseController
response.setContentType("application/octet-stream; charset=UTF-8");
IOUtils.write(data, response.getOutputStream());
}
@GetMapping("/prefixCode/{prefix}")
public String genPrefixDateCode(@PathVariable("prefix") String prefix){
// 生成任务号
return MultiModuleCodeGenerator.generateTaskCode(prefix);
}
}

View File

@ -0,0 +1,75 @@
package com.ktg.generator.util;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 根据 前缀 日期 序列号 生成编码
* @author luo26
*/
public class MultiModuleCodeGenerator {
private static final Map<String, ModuleSequence> MODULE_SEQUENCES = new ConcurrentHashMap<>();
// 生成任务编码方法
public static String generateTaskCode(String modulePrefix) {
// 获取当前日期格式为 "yyyyMMdd"
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
String currentDate = dateFormat.format(new Date());
// 获取或创建模块序列
MODULE_SEQUENCES.putIfAbsent(modulePrefix, new ModuleSequence());
ModuleSequence moduleSequence = MODULE_SEQUENCES.get(modulePrefix);
// 如果日期变化重置模块的序列号
synchronized (moduleSequence) {
if (!currentDate.equals(moduleSequence.getCurrentDate())) {
moduleSequence.setCurrentDate(currentDate);
moduleSequence.getSequence().set(0);
}
}
// 获取当前序列号并自增
int currentSequence = moduleSequence.getSequence().incrementAndGet();
// 格式化序列号确保是四位不足的地方用 0 填充
String sequenceStr = String.format("%04d", currentSequence);
// 拼接前缀日期和序列号
return modulePrefix + currentDate + sequenceStr;
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println(generateTaskCode("RKT"));
System.out.println(generateTaskCode("MOD"));
}
}
}
// 模块序列管理类
class ModuleSequence {
// 当前日期
private String currentDate;
// 序列号
private AtomicInteger sequence;
public ModuleSequence() {
this.currentDate = "";
this.sequence = new AtomicInteger(0);
}
public String getCurrentDate() {
return currentDate;
}
public void setCurrentDate(String currentDate) {
this.currentDate = currentDate;
}
public AtomicInteger getSequence() {
return sequence;
}
}

View File

@ -52,6 +52,10 @@
<artifactId>swagger-models</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>com.ktg</groupId>
<artifactId>ktg-generator</artifactId>
</dependency>
</dependencies>
</project>