Redis - 日期流水号

本文介绍了如何利用Redis来生成基于日期的流水号,详细解析了配置信息和IDGeneratorUtil工具类的使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、配置信息

<!--redis-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
  redis:
    # redis 服务器地址
    host: 127.0.0.1
    # 端口
    port: 6379
    # 链接超时时间
    timeout: 5000
    jedis:
      pool:
        # 连接池最大连结数
        max-active: 8
        # 连接池最大阻塞时间
        max-wait: 1
        # 连接池中最大空闲链接
        max-idle: 8
        # 连接池中最小空闲链接
        min-idle: 0

2、IDGeneratorUtil

package com.example.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

public class IDGeneratorUtil {
    private static StringRedisTemplate template = SpringUtil.getBean(StringRedisTemplate.class);

    /**
     * 通过redis生成自增号
     *
     * @param pre       前缀
     * @param length    序号长度
     * @param increment 是否自增
     * @param isDate    是否只获得年月
     * @return 前缀-日期-序号
     */
    public static String getRedisNo(String pre, int length, boolean increment, boolean isDate) {
        //日期
        String date;
        if (isDate) {
            date = LocalDate.now().getYear() + "" + LocalDate.now().getMonthValue();
        } else {
            date = LocalDate.now().format(DateTimeFormatter.ISO_DATE).replace("-", "");
        }

        //编号
        String key = pre + date;
        String no;

        if (increment) {
            //自增获取
            Long temp = template.opsForValue().increment(key, 1);
            if (temp == 1) {
                //过期时间,一天
                template.expire(key, isDate ? 30 : 1, TimeUnit.DAYS);
            }
            no = temp.toString();
        } else {
            //非自增获取
            no = template.opsForValue().get(key);
            if (StringUtils.isEmpty(no)) {
                no = Objects.requireNonNull(template.opsForValue().increment(key, 1)).toString();
                template.expire(key, isDate ? 30 : 1, TimeUnit.DAYS);
            }
        }

        if (no.length() >= length) {
            return key + no;
        } else {
            StringBuilder temp = new StringBuilder();
            for (int i = 0; i < length - no.length(); i++) {
                temp.append("0");
            }
            return key + temp.toString() + no;
        }


    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值