1. 程式人生 > 其它 >根據redis 自增方法生成訂單號

根據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;
    }


}