Suggest a feature
×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Java
Posted by: geng david
Added: Jan 25, 2021 6:26 AM
Views: 7
Tags: no tags
  1. private static final ThreadPoolTaskExecutor TASK_EXECUTOR;
  2.  
  3.     private static final int STORE_MAX_RESERVE_COUNT = 3;
  4.     private static final int CODE_POOL_START = 100000;
  5.     private static final int CODE_POOL_END = 1000000;
  6.  
  7.  
  8.     static {
  9.         TASK_EXECUTOR = new ThreadPoolTaskExecutor();
  10.         int core = Runtime.getRuntime().availableProcessors();
  11.         TASK_EXECUTOR.setCorePoolSize(core);
  12.         TASK_EXECUTOR.setMaxPoolSize(core * 2 + 1);
  13.         TASK_EXECUTOR.setKeepAliveSeconds(3);
  14.         TASK_EXECUTOR.setQueueCapacity(40);
  15.         TASK_EXECUTOR.setThreadNamePrefix("box-reservation-service");
  16.         TASK_EXECUTOR.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
  17.         TASK_EXECUTOR.initialize();
  18.     }
  19.  
  20.  
  21.     private String getOpenCode(Long boxId) {
  22.         String key = DeviceConstants.BOX_OPEN_CODE_POOL_PREFIX + boxId;
  23.         long size = redisUtil.opSetSize(key);
  24.         if (size < DeviceConstants.BOX_OPEN_CODE_POOL_THRESHOLDS) {
  25.             // 容量不太多了,异步去补
  26.             TASK_EXECUTOR.execute(() -> {
  27.                 List<Integer> states = new ArrayList<>();
  28.                 states.add(BoxReservation.BoxReservationState.RESERVED.getCode());
  29.                 states.add(BoxReservation.BoxReservationState.OCCUPIED.getCode());
  30.                 states.add(BoxReservation.BoxReservationState.OVERTIME.getCode());
  31.                 LambdaQueryWrapper<BoxReservation> queryWrapper = new LambdaQueryWrapper<>();
  32.                 queryWrapper.in(BoxReservation::getState, states);
  33.                 List<BoxReservation> list = reservationMapper.selectList(queryWrapper);
  34.                 Set<String> availableCodes = new HashSet<>();
  35.                 for (BoxReservation box : list) {
  36.                     availableCodes.add(box.getOpenCode());
  37.                 }
  38.                 for (int i = CODE_POOL_START; i < CODE_POOL_END; i++) {
  39.                     String code = String.valueOf(i);
  40.                     if (availableCodes.contains(code)) {
  41.                         continue;
  42.                     }
  43.                     redisUtil.opSetAddEle(key, String.valueOf(i));
  44.                 }
  45.             });
  46.         }
  47.         String code = redisUtil.opSetRandGet(key);
  48.         redisUtil.opSetRemoveEle(key, code);
  49.         return code;
  50.     }