package org.gin.utils;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;@Component
public class OrderNumBuilder {@Autowiredprivate RedisTemplate<String, Long> customRedisTemplate;private static final String ORDER_NUMBER_PREFIX = "";private static final String REDIS_ORDER_NUMBER_KEY = "gin:orderNo";private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyMMdd");private static final Lock lock = new ReentrantLock();public String getOrderNo() {lock.lock();String orderNo = null;try {Object exitOrderNo=customRedisTemplate.opsForValue().get(REDIS_ORDER_NUMBER_KEY);if (exitOrderNo==null) {customRedisTemplate.opsForValue().set(REDIS_ORDER_NUMBER_KEY, Long.valueOf(LocalDateTime.ofInstant(new Date().toInstant(), ZoneId.systemDefault()).format(dateTimeFormatter) + "00000"));}long currentOrder = customRedisTemplate.opsForValue().increment(REDIS_ORDER_NUMBER_KEY, 1L);long current = Long.valueOf(String.valueOf(currentOrder).substring(0, 6)); long now = Long.valueOf(LocalDateTime.ofInstant(new Date().toInstant(), ZoneId.systemDefault()).format(dateTimeFormatter));if (current != now) {if (now < current) {while (true) {now = Long.valueOf(LocalDateTime.ofInstant(new Date().toInstant(), ZoneId.systemDefault()).format(dateTimeFormatter));if (now == current) {customRedisTemplate.opsForValue().set(REDIS_ORDER_NUMBER_KEY, Long.valueOf(now + "00000"));orderNo = ORDER_NUMBER_PREFIX + customRedisTemplate.opsForValue().increment(REDIS_ORDER_NUMBER_KEY, 1L);break;}}} else {customRedisTemplate.opsForValue().set(REDIS_ORDER_NUMBER_KEY, Long.valueOf(now + "00000"));orderNo = ORDER_NUMBER_PREFIX + customRedisTemplate.opsForValue().increment(REDIS_ORDER_NUMBER_KEY, 1L);}} else {orderNo = ORDER_NUMBER_PREFIX + currentOrder;}} catch (Exception e) {e.printStackTrace();} finally {lock.unlock();}return orderNo;}
}