Redis教程

利用redis生成流水号

本文主要是介绍利用redis生成流水号,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Component
public class PrimaryGenerator {

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * redis任务流水号key
     */
    private final static String REDIS_TASK_KEY = "serial";

    private final static String TASK_PREFIX = "T";

    public synchronized String createTaskNo(int codeLength) {
        String dateStr = getDateStr();
        String key = REDIS_TASK_KEY + dateStr;
        String noPrefix = TASK_PREFIX + dateStr;
        Long count = redisTemplate.opsForValue().increment(key, 1);
        redisTemplate.boundValueOps(key).expire(1, TimeUnit.DAYS);
        String code = addZeroForNum(count.toString(), codeLength - noPrefix.length());
        // 最终结果
        return noPrefix + code;
    }
    private String getDateStr() {
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        return formatter.format(date);
    }

    private String addZeroForNum(String str, int strLength) {
        int strLen = str.length();
        if (strLen < strLength) {
            while (strLen < strLength) {
                StringBuffer sb = new StringBuffer();
                sb.append("0").append(str);// 左补0
                str = sb.toString();
                strLen = str.length();
            }
        }
        return str;
    }
}

 

这篇关于利用redis生成流水号的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!