生成流水号可以有很多方式,此文章采用redis 键自增的方式哦

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author wuzhenyong
 * ClassName:SerialUtil.java
 * date:2022-04-26 8:21
 * Description: 流水号工具类
 */
@Component
public class SerialUtil {
    /**
     * redis流水号key
     */
    private final static String REDIS_KEY = "serial";
    /**
     * 流水号抬头
     */
    private final static String STR = "LSH";
    /**
     * 流水号格式
     */
    private final static String FORMAT_CODE = "0000";

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 生成流水号
     * 实际业务需要检查数据库是否存在
     * @return {@link String}
     */
    public String nextValue() {

        LocalDateTime now = LocalDateTime.now();
        // 格式在这里定义
        String pattern = "yyyyMMdd";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        String date = formatter.format(now);
        DecimalFormat dft = new DecimalFormat(FORMAT_CODE);
        Long count = redisTemplate.opsForValue().increment(REDIS_KEY, 1);
        // 格式化为四位流水号
        String code = dft.format(count);
        // 最终结果
        String result = STR + date + code;
        return result;
    }

}

调用生成流水号的方法
例子:当前时间2022-05-20
流水号为:LSH202205200001 前缀+日期+四位数(自增的方式)

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐