/**
* 序列号生成器
* 生成结果位:2位站点id + 模型CODE(3位) + 时间日期(年月日 8位)+ 序列号(固定8位,不足补零)
*/
public class SequenceService {
private static final Logger logger = LoggerFactory.getLogger(SequenceService.class);
@Autowired
private SequenceMapper SequenceMapper;
@Autowired
private TransactionTemplate transactionTemplate;
private ConcurrentHashMap<String, StepValue> stepValueMap = new ConcurrentHashMap<>();
class StepValue {
/**
* 当前可用的id值
*/
protected Long currentValue = null;
/**
* 当前可用最大id值
*/
protected Long maxValue = null;
}
/**
* 获取id
*
* @param name id编号:例:CASE_ID
* @return
*/
public String getNextSeqValue(String name) {
return CCTransactionTemplate.execute(status -> {
StepValue stepValue = stepValueMap.get(name);
if (stepValue != null) {
synchronized (stepValue) {
if (stepValue.currentValue < stepValue.maxValue) {
stepValue.currentValue++;
return StringUtils.leftPad(stepValue.currentValue.toString(), 8, '0');
}
}
} else {
stepValue = new StepValue();
}
// 从数据库获取新的currentId和maxId
CCSequence CCSequence = SequenceMapper.selectByPrimaryKeyForUpdate(name);
if (CCSequence == null) {
// 新增序列号id
CCSequence CCSequenceInsert = new CCSequence();
CCSequenceInsert.setName(name);
CCSequenceInsert.setValue(1L);
CCSequenceInsert.setMinValue(1);
CCSequenceInsert.setMaxValue(99999999);
CCSequenceInsert.setStep(1000);
SequenceMapper.insertSelective(CCSequenceInsert);
CCSequence = SequenceMapper.selectByPrimaryKeyForUpdate(name);
}
// 数据库可用id耗尽,重新从0开始
if (CCSequence.getValue() + CCSequence.getStep() > CCSequence.getMaxValue()) {
CCSequence.setValue(1L);
}
stepValue.currentValue = CCSequence.getValue();
stepValue.maxValue = stepValue.currentValue + CCSequence.getStep();
CCSequence.setValue(stepValue.maxValue);
// 更新数据库
SequenceMapper.updateByPrimaryKey(CCSequence);
stepValueMap.put(name, stepValue);
return StringUtils.leftPad(stepValue.currentValue.toString(), 8, '0');
});
}
public String getNextCaseId() {
String modelId = CCModelIdEnum.CASE_ID.getCode() + TimeUtil.timeFormat_yyyyMMdd(new Date())
+ getNextSeqValue(CCModelIdEnum.CASE_ID.getSeqName());
return modelId;
}
}
序列号生成器
于 2022-08-29 14:14:11 首次发布