Commit fc56df65 authored by LiuLin's avatar LiuLin

fix(ymt):登记使用证生成

parent 6ff62da9
package com.yeejoin.amos.boot.module.ymt.api.common;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.Date;
public class DateUtils {
public static Date calculateEndOfYear(Date currentDate) {
LocalDateTime localDateTime = toLocalDateTime(currentDate);
LocalDateTime endOfYear = localDateTime.with(LocalDateTime.of(localDateTime.getYear(), 12, 31, 23, 59, 59, 999999999));
return toDate(endOfYear);
}
public static Date calculateEndOfMonth(Date currentDate) {
LocalDateTime localDateTime = toLocalDateTime(currentDate);
LocalDateTime endOfMonth = localDateTime.with(localDateTime.withDayOfMonth(localDateTime.getMonth().maxLength())
.withHour(23)
.withMinute(59)
.withSecond(59)
.withNano(999999999));
return toDate(endOfMonth);
}
public static Date calculateEndOfDay(Date currentDate) {
LocalDateTime localDateTime = toLocalDateTime(currentDate);
LocalDateTime endOfDay = localDateTime.with(LocalDateTime.of(localDateTime.toLocalDate(), LocalTime.MAX));
return toDate(endOfDay);
}
private static LocalDateTime toLocalDateTime(Date date) {
return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
}
private static Date toDate(LocalDateTime localDateTime) {
return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
}
}
//package com.yeejoin.amos.boot.module.ymt.api.controller;
//
//import com.yeejoin.amos.boot.biz.common.controller.BaseController;
//import com.yeejoin.amos.boot.module.ymt.api.service.ICreateCodeService;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiOperation;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.web.bind.annotation.*;
//import org.typroject.tyboot.core.foundation.enumeration.UserType;
//import org.typroject.tyboot.core.restful.doc.TycloudOperation;
//import org.typroject.tyboot.core.restful.utils.ResponseHelper;
//import org.typroject.tyboot.core.restful.utils.ResponseModel;
//import java.util.List;
//
///**
// *
// * 生成顺序码
// * @author LiuLin
// * @date 2023-12-14
// */
//@RestController
//@Api(tags = "生成顺序码")
//@RequestMapping(value = "/code")
//public class CreateCodeController extends BaseController {
//
// @Autowired
// private ICreateCodeService createCodeService;
//
// /**
// * 申请单编号生成
// * @param type type
// * @param batchSize batchSize
// * @return List
// */
// @TycloudOperation(ApiLevel = UserType.AGENCY)
// @PostMapping(value = "/ANCode")
// @ApiOperation(httpMethod = "POST", value = "申请单编号生成", notes = "申请单编号生成")
// public ResponseModel<List<String>> createANCode(@RequestParam("type") String type,
// @RequestParam("batchSize") int batchSize) {
// return ResponseHelper.buildResponse(createCodeService.createApplicationFormCode(type,batchSize));
// }
//
// /**
// * 生成设备注册编码
// * @param key key
// * @return String
// */
// @TycloudOperation(ApiLevel = UserType.AGENCY)
// @PostMapping(value = "/DRCode")
// @ApiOperation(httpMethod = "POST", value = "生成设备注册编码", notes = "生成设备注册编码")
// public ResponseModel<String> createDRCode(@RequestParam("key") String key) {
// return ResponseHelper.buildResponse(createCodeService.createDeviceRegistrationCode(key));
// }
//
// /**
// * 使用登记证生成
// * @param key key
// * @return String
// */
// @TycloudOperation(ApiLevel = UserType.AGENCY)
// @PostMapping(value = "/URCode")
// @ApiOperation(httpMethod = "POST", value = "使用登记证生成", notes = "使用登记证生成")
// public ResponseModel<String> createURCode(@RequestParam("key") String key) {
// return ResponseHelper.buildResponse(createCodeService.createUseRegistrationCode(key));
// }
//}
......@@ -2,6 +2,11 @@ package com.yeejoin.amos.boot.module.ymt.api.service;
import java.util.List;
/**
* 生成码服务类
* @author LiuLin
* @date 2023-12-14
*/
public interface ICreateCodeService {
/**
......@@ -20,4 +25,11 @@ public interface ICreateCodeService {
*/
String createDeviceRegistrationCode(String key);
/**
* 生成使用登记证编号(13位,起11陕C00001(23))
* @param key key
* @return 顺序编号
*/
String createUseRegistrationCode(String key);
}
package com.yeejoin.amos.boot.module.ymt.api.service.impl;
import com.yeejoin.amos.boot.module.ymt.api.common.DateUtils;
import com.yeejoin.amos.boot.module.ymt.api.enums.ApplicationFormTypeEnum;
import com.yeejoin.amos.boot.module.ymt.api.service.ICreateCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
......@@ -14,12 +16,17 @@ import java.util.concurrent.TimeUnit;
* @author LiuLin
* @date 2023-12-14
*/
@Slf4j
@Service
public class CreateCodeServiceImpl implements ICreateCodeService {
private static final String LOCK_VALUE = "locked";
private static final String LOCK_KEY_AF = "sequence_lock_af";
private static final String SEQUENCE_TYPE_AF = "%03d";
private static final String LOCK_KEY_DR = "sequence_lock_dr";
private static final String SEQUENCE_TYPE_DR = "%04d";
private static final String LOCK_KEY_UR = "sequence_lock_ur";
private static final String SEQUENCE_TYPE_UR = "%05d";
private final RedisTemplate<String, String> redisTemplate;
private String rulePrefix;
......@@ -27,6 +34,13 @@ public class CreateCodeServiceImpl implements ICreateCodeService {
this.redisTemplate = redisTemplate;
}
/**
* 生成申请单编号(13位,GZ20231214000)
*
* @param type 枚举类型
* @param batchSize 生成个数
* @return List
*/
@Override
public List<String> createApplicationFormCode(String type, int batchSize) {
if (!isValueInEnum(type)) {
......@@ -36,17 +50,48 @@ public class CreateCodeServiceImpl implements ICreateCodeService {
return generateBatchSequence(type, batchSize);
}
/**
* 生成设备注册编码(20位)
*
* @param key key
* @return 顺序编号
*/
@Override
public String createDeviceRegistrationCode(String key) {
return generateSequence(key);
return generateSequence(key, SEQUENCE_TYPE_DR, LOCK_KEY_DR);
}
/**
* 生成使用登记证编号(13位,起11陕C00001(23))
*
* @param key key
* @return 顺序编号
*/
@Override
public String createUseRegistrationCode(String key) {
rulePrefix = "(" + LocalDate.now().format(DateTimeFormatter.ofPattern("yy")) + ")";
return generateSequence(key, SEQUENCE_TYPE_UR, LOCK_KEY_UR);
}
/**
* 校验枚举合法性
*
* @param value value
* @return bool
*/
public boolean isValueInEnum(String value) {
return EnumSet.allOf(ApplicationFormTypeEnum.class)
.stream()
.anyMatch(enumValue -> enumValue.name().equals(value));
}
/**
* 批量生成顺序码
*
* @param sequenceKey sequenceKey
* @param batchSize 批量生成个数
* @return List
*/
public List<String> generateBatchSequence(String sequenceKey, int batchSize) {
// 使用分布式锁,确保在并发情况下只有一个线程能够生成顺序码
Boolean lockAcquired = redisTemplate.opsForValue().setIfAbsent(LOCK_KEY_AF, LOCK_VALUE);
......@@ -57,21 +102,19 @@ public class CreateCodeServiceImpl implements ICreateCodeService {
String currentSequenceStr = valueOps.get(sequenceKey);
// 如果为空,则初始化为0
if (currentSequenceStr == null) {
currentSequenceStr = "0";
}
// 将当前顺序码加1
Long currentSequence = Long.parseLong(currentSequenceStr);
Long currentSequence = (currentSequenceStr != null) ? Long.parseLong(currentSequenceStr) : 0L;
log.info("===================>获取《{}》当前顺序码:{}<===================", sequenceKey, currentSequenceStr);
// 生成批量顺序码
List<String> sequenceList = new ArrayList<>();
log.info("===================>批量生成{}个《{}》顺序码<===================", batchSize, sequenceKey);
for (int i = 0; i < batchSize; i++) {
currentSequence++;
// 生成3位顺序码
String formattedSequence = String.format("%03d", currentSequence);
String formattedSequence = String.format(SEQUENCE_TYPE_AF, currentSequence);
sequenceList.add(rulePrefix + formattedSequence);
// 更新顺序码
log.info("===================>更新《{}》顺序码:{}<===================", sequenceKey, formattedSequence);
setValueWithDailyExpiration(sequenceKey, String.valueOf(formattedSequence));
}
......@@ -85,85 +128,114 @@ public class CreateCodeServiceImpl implements ICreateCodeService {
}
}
public String generateSequence(String sequenceKey) {
/**
* 批量生成顺序码
*
* @param sequenceKey redisKey
* @param sequenceType 生成码类型
* @param lockKey redis锁
* @return s
*/
public String generateSequence(String sequenceKey, String sequenceType, String lockKey) {
// 使用分布式锁,确保在并发情况下只有一个线程能够生成顺序码
Boolean lockAcquired = redisTemplate.opsForValue().setIfAbsent(LOCK_KEY_DR, LOCK_VALUE);
Boolean lockAcquired = obtainLock(lockKey);
if (Boolean.TRUE.equals(lockAcquired)) {
try {
// 获取当前顺序码
ValueOperations<String, String> valueOps = redisTemplate.opsForValue();
String currentSequenceStr = valueOps.get(sequenceKey);
// 如果为空,则初始化为0
if (currentSequenceStr == null) {
currentSequenceStr = "0";
}
// 将当前顺序码加1
Long currentSequence = Long.parseLong(currentSequenceStr);
Long currentSequence = (currentSequenceStr != null) ? Long.parseLong(currentSequenceStr) : 0L;
log.info("===================>获取《{}》当前顺序码:{}<===================", sequenceKey, currentSequenceStr);
currentSequence++;
// 生成顺序码
String formattedSequence = String.format(sequenceType, currentSequence);
log.info("===================>更新《{}》顺序码:{}<===================", sequenceKey, formattedSequence);
// 更新顺序码
if (sequenceType.equals(LOCK_KEY_DR)) {
setValueWithMonthlyExpiration(sequenceKey, String.valueOf(formattedSequence));
} else {
setValueWithYearlyExpiration(sequenceKey, String.valueOf(formattedSequence));
}
// 生成10位顺序码
String formattedSequence = String.format("%04d", currentSequence);
String generatedSequence = sequenceKey + formattedSequence;
String result = generatedSequence + (sequenceType.equals(LOCK_KEY_DR) ? "" : rulePrefix);
// 更新顺序码
setValueWithMonthlyExpiration(sequenceKey, String.valueOf(formattedSequence));
log.info("===================>返回《{}》顺序码:{}<===================", sequenceKey, result);
return result;
return sequenceKey + formattedSequence;
} finally {
redisTemplate.delete(LOCK_KEY_DR);
releaseLock(lockKey);
}
} else {
// 获取锁失败,可以选择重试或采取其他策略
throw new RuntimeException("Failed to acquire lock for sequence generation");
}
}
/**
* 分布式锁
*
* @param lockKey lockKey
* @return bool
*/
private Boolean obtainLock(String lockKey) {
return redisTemplate.opsForValue().setIfAbsent(lockKey, LOCK_VALUE);
}
/**
* 释放锁
*
* @param lockKey lockKey
*/
private void releaseLock(String lockKey) {
redisTemplate.delete(lockKey);
}
/**
* redis 根据自然日过期
*
* @param key key
* @param value value
*/
public void setValueWithDailyExpiration(String key, String value) {
Date endOfDay = DateUtils.calculateEndOfDay(new Date());
setValueWithExpiration(key, value, endOfDay);
}
/**
* redis 根据自然月过期
*
* @param key key
* @param value value
*/
public void setValueWithMonthlyExpiration(String key, String value) {
ValueOperations<String, String> valueOps = redisTemplate.opsForValue();
valueOps.set(key, value);
Date currentDate = new Date();
Date endOfMonth = calculateEndOfMonth(currentDate);
long expirationTimeInSeconds = endOfMonth.getTime() - currentDate.getTime();
Date endOfMonth = DateUtils.calculateEndOfMonth(new Date());
setValueWithExpiration(key, value, endOfMonth);
}
redisTemplate.expire(key, expirationTimeInSeconds, TimeUnit.MILLISECONDS);
/**
* redis 根据自然年过期
*
* @param key key
* @param value value
*/
public void setValueWithYearlyExpiration(String key, String value) {
Date endOfYear = DateUtils.calculateEndOfYear(new Date());
setValueWithExpiration(key, value, endOfYear);
}
public void setValueWithDailyExpiration(String key, String value) {
/**
* redis设置key
*
* @param key key
* @param value value
* @param expirationDate 过期时间
*/
public void setValueWithExpiration(String key, String value, Date expirationDate) {
ValueOperations<String, String> valueOps = redisTemplate.opsForValue();
valueOps.set(key, value);
Date currentDate = new Date();
Date endOfDay = calculateEndOfDay(currentDate);
long expirationTimeInSeconds = endOfDay.getTime() - currentDate.getTime();
long expirationTimeInSeconds = expirationDate.getTime() - System.currentTimeMillis();
redisTemplate.expire(key, expirationTimeInSeconds, TimeUnit.MILLISECONDS);
}
private Date calculateEndOfMonth(Date currentDate) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(currentDate);
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
return calendar.getTime();
}
private Date calculateEndOfDay(Date currentDate) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(currentDate);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
return calendar.getTime();
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment