美文网首页
实战篇-Redis生成自增长订单号

实战篇-Redis生成自增长订单号

作者: 艺术类架构师 | 来源:发表于2019-06-21 17:46 被阅读0次

    @Autowired
    RedisTemplate redisTemplate;

    static final String REDIS_INC_KEY="key";

    /**
     * 用Redis计数器生成订单号,生成规则:前缀+年月日+Redis自增长序列号
     * 劣势:依赖于Redis,消耗带宽,消耗流量.
     * 优势:保证有序,而且每天的订单号增长都是从1开始自增的
     * @param prefix 前缀字符
     * @return 订单号 eg:Order201906110002
     */
    public String genOrderNoByRedis(String prefix){
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(REDIS_INC_KEY, redisTemplate.getConnectionFactory());
        Long increment = entityIdCounter.getAndIncrement()+1;
        Date today=new Date();
        Calendar cs=Calendar.getInstance();
        cs.setTime(today);
        //凌晨过期
        cs.add(Calendar.DAY_OF_MONTH,1);
        cs.set(Calendar.HOUR_OF_DAY,0);
        cs.set(Calendar.MINUTE,0);
        cs.set(Calendar.SECOND,0);
        //设置第二天的凌晨00:00为失效期
        entityIdCounter.expireAt(cs.getTime());
        System.out.println(FastDateFormat.getInstance("yyyyMMddHHmmss").format(cs.getTime()));
        //补四位,缺失的位置用0补位
        String  importantKey=increment.toString();
        if(importantKey.length()<4) {
            importantKey = "0000".substring(0,4-importantKey.length())+importantKey;
        }
        //
        String orderNO=String.format("%s%s%s",prefix, FastDateFormat.getInstance("yyyyMMdd").format(today),importantKey);
        return orderNO;

    }

相关文章

网友评论

      本文标题:实战篇-Redis生成自增长订单号

      本文链接:https://www.haomeiwen.com/subject/oaeuqctx.html