http://xiangai.taobao.com
http://shop148612228.taobao.com

redis实现流水号

@Component
public class CreateCodeUtils {

    @Autowired
    private RedisUtils redisUtils;

    //生成code的长度
    private static final int codeLength = 12;
    //过期时间
    private static final int expirationTime = 60 * 60 * 24;
    /**
     * type标明业务类型
     */
    public String createCode(String type) {
        SimpleDateFormat sd = new SimpleDateFormat("yyyyMMdd");
        //日期code
        String dateCode = sd.format(new Date());
        //redis里的key
        String key = dateCode + type;
        //redis的code
        String code = "";
        //查询是否存在这个key
        Boolean flag = redisUtils.hasKey(key);
        //生成的code值
        String resultCode = "";
        if (flag) {

            code = String.valueOf(redisUtils.incr(key, 1));

            int length = codeLength - 8 - (code.length());
            //拼接code前边的0
            String ling = "";
            for (int i = 0; i < length; i++) {
                ling += "0";
            }

            resultCode = dateCode + ling + code;

        } else {
            resultCode = dateCode + "0001";
            redisUtils.set(key, 1, expirationTime);
        }
        return resultCode;
    }

}
posted @ 2021-08-10 14:39  万事俱备就差个程序员  阅读(555)  评论(0编辑  收藏  举报

http://xiangai.taobao.com
http://shop148612228.taobao.com
如果您觉得对您有帮助.领个红包吧.谢谢.
支付宝红包
微信打赏 支付宝打赏