根据redis 自增方法生成订单号


package com.leshu.framework.util;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @program: brand-website-client
 * @description: 创建订单id工具类
 * @author: dong.chang
 * @create: 2021-03-18 15:10
 **/
@Component
public class CreateOrderIdUtils {

    @Resource
    private RedisTemplate<String, Serializable> redisTemplate;

    public static String getOrderIdPrefix(LocalDateTime now) {
        return now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
    }

    /**
     * 获取有过期时间的自增长ID
     *
     * @param key
     * @param expireTime
     * @return
     */
    public long generate(String key, Date expireTime) {
        RedisAtomicLong counter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        Long expire = counter.getExpire();
        if (expire == -1) {
            counter.expireAt(expireTime);
        }
        return counter.incrementAndGet();
    }

    //todo 分布式情况下 当前日期后边加上当前服务器id
    public String generateOrderId() {
        //生成id为当前日期(yyMMddHHmmss)+6位(从000000开始不足位数补0)
        LocalDateTime now = LocalDateTime.now();
        //生成yyyyMMddHHmmss
        String orderIdPrefix = getOrderIdPrefix(now);
        String orderId = orderIdPrefix + String.format("%1$06d", generate(orderIdPrefix, getExpireAtTime(now)));
        return orderId;

    }

    public Date getExpireAtTime(LocalDateTime now) {
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime localDateTime = now.plusSeconds(20);
        ZonedDateTime zdt = localDateTime.atZone(zoneId);
        Date date = Date.from(zdt.toInstant());
        return date;
    }


}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM