java特殊编码生成

工作中想要生成一个特殊编码,比如:SZ-2412030009,前面三位是编码固定开头,然后是yyMMdd,最后是当天的个数。

期望能够生成一个计算当天task个数,第二天重新计数的一个编码,用于插入到数据库中作为特殊标识。便于用户快速查看任务时间和个数

    
    @Resource
    private RedisTemplate<String, Long> redisTemplate;

    @Override
    public String getLastVersionCode() {
        SimpleDateFormat df = new SimpleDateFormat("yyMMdd");
        // 当天的key是相同的,比如SZ-231107,当天的key一直会是这个
        String code = "SZ-" + df.format(new Date());

        // 个数递增,如果不存在,设置为1
        Long versionNumByToday = redisTemplate.opsForValue().increment(code, 1);

        // Redis本身是有持久化的,即使重启服务器也不用担心redis数据丢失
        // 但是问题在于,项目之前的设计并不好,给用户和其他人员配备了缓存清理功能,会导致redis数据丢失。
        // 所以如果key不存在的情况,也有可能是缓存被清理,所以这里要判断一下(特殊业务处理)
        if (versionNumByToday == 1L) {

            // 如果没有上述的特殊情况,不用设置以下两行
            versionNumByToday = getVersionNumByToday(code);
            redisTemplate.opsForValue().set(code, versionNumByToday);

            // 设置 Redis 键的过期时间为 1 天
            redisTemplate.expire(code, 1, TimeUnit.DAYS);
        }
        DecimalFormat decimalFormat = new DecimalFormat("0000");
        String newCode = decimalFormat.format(versionNumByToday);

        newCode = code + newCode;
        return newCode;
    }

    private Long getVersionNumByToday(String code) {
        Long versionNumByToday = null;
        // 从数据库中获取最新的编号
        String latestVersionCode = getLatestVersionCodeFromDatabase();
        if (latestVersionCode != null && latestVersionCode.startsWith(code)) {
            // 解析最新的编号,提取出编号部分
            String latestVersionCodePrefix = latestVersionCode.substring(9);
            // 设置 Redis 中的计数器为最新的编号 + 1
            versionNumByToday = Long.parseLong(latestVersionCodePrefix) + 1L;
        } else {
            // 如果数据库中没有编号,设置 Redis 计数器为 1
            versionNumByToday = 1L;
        }
        return versionNumByToday;
    }

    /**
     * 从数据库中获取最新的编号
     *
     * @return 最新的编号
     */
    private String getLatestVersionCodeFromDatabase() {
        // 假设 version_code 字段存储了编号
        QueryWrapper<ShequnAiFileManager> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("version").last("limit 1");
        ShequnAiFileManager latestRecord = this.getOne(queryWrapper);
        return latestRecord != null ? latestRecord.getVersion() : null;
    }

注:使用@Resource引入RedisTemplate,因为我们设置了泛型的。

references:

https://blog.csdn.net/victo_chao/article/details/120438648

posted @   在成长的土拨鼠  阅读(8)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示