简单流水号生成器

简单的流水号生成器,可以照顾到并发和多节点部署

@Component
public class SerialNumberGenerator {

    private static Logger log = LogManager.getLogger(SerialNumberGenerator.class.getName());
    
    //系统id,取配置文件中配置参数.多个节点可配置不同参数
    @Value("${credit.system.key}")
    private String systemKey;

    //原子操作类
    private static AtomicInteger count = new AtomicInteger(0);

    public String getSerialNumber() throws BusinessException {
        if(StringUtils.isBlank(systemKey)){
            log.error("SerialNumberGenerator getSerialNumber systemKey is null ");
            throw new BusinessException(ErrorEnum.SYSTEM_ERROR);
        }
        if(count.get() == 10000){
            count.set(0);
        }
        //当前日期
        String currentTime = DateUtils.getDateByFormate(new Date(),DateUtils.DATE_FORMAT);
        //当前值,并补位0
        String currentIndex =String.format("%05d", count.get());
        String serialNumber = systemKey+currentTime+currentIndex;

        log.info("SerialNumberGenerator getSerialNumber is:"+ serialNumber );
        //++
        count.incrementAndGet();
        return serialNumber;
    }
}

你可能感兴趣的:(java)