利用Redis实现编码生成规则

一.适用场景:

新增数据后自动生成编码,生成规则为MD + 年月日 + 4位序列号,如MD202310130001

二.场景分析:

此场景需要注意的就是后四位序列号如果使用随机4位数字,极大可能会生成重复的编码,从而影响整个业务,所以最好是使用从0开始自增,不仅避免的随机生成重复编码的可能,而且还方便使用人员根据编码获取到有用信息。

三.功能实现:


    private static final String PREFIX = "MD"; // 前缀
    private static final String DATE_FORMAT = "yyyyMMdd"; // 年月日格式
    /**
     * 利用Redis生成编码 (MD202310130001)
     * @return
     */
    private String generateTemplateNumber(){
        SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
        String currentDate = dateFormat.format(new Date());
        //组装Redis的key(自定义字符串 + 当天的时间)
        String key = String.format(RedisKeyConstants.TASK_TEMPLATE_CODE, currentDate);
        Integer cache = cacheService.getCache(key, Integer.class);
        String templateCode = generateTemplateCode(cache);
        cacheService.incrBy(key,NumberUtils.INTEGER_ONE,ONE_DAY);
        return templateCode;
    }



    /**
     * 根据当前最大值生成编码(可写在工具类中)
     * @return
     */
    public String generateTemplateCode(Integer num) {
        if (ObjectUtils.isEmpty(num)){
            num = 0;
        }
        AtomicInteger sequence = new AtomicInteger(num);
        // 获取当前日期
        SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
        String currentDate = dateFormat.format(new Date());
        // 生成4位序列号
        int currentSequence = sequence.incrementAndGet();
        String sequenceStr = String.format("%04d", currentSequence);

        // 组装编码
        return PREFIX + currentDate + sequenceStr;
    }

四.总结:

相比查询数据库中编码的最大值,然后再+1,效率更加高,代码实现难度更加低,因为查询数据库最大值,然后+1,可能要考虑不同天日期的处理,总之,下次遇到有这样类似编码生成的需求,直接用Redis的incrBy是不错之举

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值