Redis 通过 increment 生成自增 订单号

原理 就是 利用 increment 原子增加操作

@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTest {

   @Autowired
   private StringRedisTemplate stringRedisTemplate;

   private static final String ORDER_NUMBER_PREFIX = "0";
   private static final String REDIS_ORDER_NUMBER_KEY = "orderNo";
   private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
   private static final Lock lock = new ReentrantLock();
   private static List list = Collections.synchronizedList(new ArrayList<>());


   /**
    * 20121212121212 + 3位递增
    */
   @Test
   public void test() throws InterruptedException {

       int count = 2000;

       CyclicBarrier barrier = new CyclicBarrier(count, () -> {
           try {
               System.out.println(" 全部就位... ");
               System.out.println(" 3");
               Thread.sleep(1000);
               System.out.println(" 2");
               Thread.sleep(1000);
               System.out.println(" 1");
               Thread.sleep(1000);
               System.out.println(" 开始 GO.");
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       });

       ExecutorService executor = Executors.newFixedThreadPool(count);

       for (int i = 0; i < count; i++) {

           executor.execute(() -> {

               try {

                   System.out.println("Thread " + Thread.currentThread().getName() + "就位");
                   barrier.await();
                   System.out.println("Thread " + Thread.currentThread().getName() + "执行");
                   getOrderNo();

               } catch (Exception e) {
                   e.printStackTrace();
               }

           });
       }

       //保证所有线程执行完毕
       Thread.sleep(600000);
       executor.shutdown();
   }

   private String getOrderNo() {


       lock.lock();

       String orderNo = null;

       try {

           // 获取redis此时订单号
           if (StringUtils.isEmpty(stringRedisTemplate.opsForValue().get(REDIS_ORDER_NUMBER_KEY))) {
               // 初始化
               stringRedisTemplate.opsForValue().set(REDIS_ORDER_NUMBER_KEY, LocalDateTime.ofInstant(new Date().toInstant(), ZoneId.systemDefault()).format(dateTimeFormatter) + "000");
           }

           // 获取当前订单号2019 0628 173739 001
           long currentOrder = stringRedisTemplate.opsForValue().increment(REDIS_ORDER_NUMBER_KEY, 1L);
           long current = Long.valueOf(String.valueOf(currentOrder).substring(0, 14));
           // 当前时间
           long now = Long.valueOf(LocalDateTime.ofInstant(new Date().toInstant(), ZoneId.systemDefault()).format(dateTimeFormatter));

           if (current != now) {
               if (now < current) {
                   
                   // 循环等待到下一秒 重新从001 开始 
                   while (true) {
                       now = Long.valueOf(LocalDateTime.ofInstant(new Date().toInstant(), ZoneId.systemDefault()).format(dateTimeFormatter));
                       if (now == current) {
                           // 重新 001 开始
                           stringRedisTemplate.opsForValue().set(REDIS_ORDER_NUMBER_KEY, now + "000");
                           orderNo = ORDER_NUMBER_PREFIX + stringRedisTemplate.opsForValue().increment(REDIS_ORDER_NUMBER_KEY, 1L);
                           break;
                       }
                   }

               } else {
                   // 重新 001 开始
                   stringRedisTemplate.opsForValue().set(REDIS_ORDER_NUMBER_KEY, now + "000");
                   orderNo = ORDER_NUMBER_PREFIX + stringRedisTemplate.opsForValue().increment(REDIS_ORDER_NUMBER_KEY, 1L);
               }

           } else {
               // 直接返回当前的订单号
               orderNo = ORDER_NUMBER_PREFIX + currentOrder;
           }


           System.out.println(LocalDateTime.now() + ":orderNo = " + orderNo + ":flag=" + list.contains(orderNo));
           list.add(orderNo);

       } catch (Exception e) {

           e.printStackTrace();

       } finally {

           lock.unlock();
       }

       return orderNo;

   }
}
2019-06-29T00:08:01.999:orderNo = 020190629000801515:flag=false
2019-06-29T00:08:02:orderNo = 020190629000802001:flag=false
2019-06-29T00:08:02.001:orderNo = 020190629000802002:flag=false

2019-06-29T00:08:02.492:orderNo = 020190629000802999:flag=false
2019-06-29T00:08:03:orderNo = 020190629000803001:flag=false
2019-06-29T00:08:03.001:orderNo = 020190629000803002:flag=false

你可能感兴趣的:(Redis 通过 increment 生成自增 订单号)