package org.dromara.eims.service.impl; 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.dromara.eims.service.IGenerateCodeService; import org.springframework.stereotype.Service; import java.time.LocalDate; import java.time.format.DateTimeFormatter; @RequiredArgsConstructor @Service public class GenerateCodeServiceImpl implements IGenerateCodeService { @Override public String generateCode(String prefix) { String key = CacheConstants.EIMS_GENERATE_CODE + ":" + prefix; String todayStr = DateTimeFormatter.ofPattern("yyyyMMdd").format(LocalDate.now()); 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); return code; } catch (Exception e) { return null; } } }