Przeglądaj źródła

initApplyAvailableCountCacheForTimePeriods

deason 8 miesięcy temu
rodzic
commit
2606540514

+ 51 - 0
src/main/java/com/qmth/exam/reserve/cache/impl/ApplyTaskCacheService.java

@@ -13,6 +13,7 @@ import com.qmth.exam.reserve.mq.ExamReserveMQProducer;
 import com.qmth.exam.reserve.service.*;
 import org.apache.commons.collections4.CollectionUtils;
 import org.apache.commons.collections4.MapUtils;
+import org.apache.commons.lang3.ArrayUtils;
 import org.redisson.api.RAtomicLong;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -275,6 +276,56 @@ public class ApplyTaskCacheService implements CacheConstants {
         }
     }
 
+    /**
+     * 初始 某些时段与所有考点的“剩余可约数量”缓存
+     */
+    public void initApplyAvailableCountCacheForTimePeriods(Long... timePeriodIds) {
+        if (ArrayUtils.isEmpty(timePeriodIds)) {
+            return;
+        }
+
+        // 获取所有考点和考点总容量集合
+        List<ExamSiteCapacityInfo> examSites = examSiteService.findAllExamSiteCapacityList();
+        if (CollectionUtils.isEmpty(examSites)) {
+            return;
+        }
+
+        for (ExamSiteCapacityInfo examSite : examSites) {
+            String lockKey = String.format(CacheConstants.LOCK_EXAM_SITE_CAPACITY, examSite.getExamSiteId());
+            Lock lock = concurrentService.getLock(lockKey);
+
+            try {
+                if (!lock.tryLock()) {
+                    log.warn("获取锁失败,不允许同时操作!{}", lockKey);
+                    return;
+                }
+
+                for (Long timePeriodId : timePeriodIds) {
+                    String cacheKey = String.format(CACHE_APPLY_AVAILABLE_COUNT, examSite.getExamSiteId(), timePeriodId);
+                    boolean existCache = redisClient.exist(cacheKey);
+                    if (existCache) {
+                        // 跳过存在的缓存
+                        continue;
+                    }
+
+                    // 获取某考点某时段的“已预约数量”
+                    int finishCount = studentApplyService.countApplyFinishForExamSiteAndTimePeriod(examSite.getExamSiteId(), timePeriodId);
+                    // 剩余可约数量
+                    int availableCount = Math.max(examSite.getCapacity() - finishCount, 0);
+                    RAtomicLong atomic = redisClient.getRedissonClient().getAtomicLong(cacheKey);
+                    atomic.set(availableCount);
+                    log.warn("初始考点时段剩余可约数量:{} {}", availableCount, cacheKey);
+                }
+            } finally {
+                try {
+                    lock.unlock();
+                } catch (Exception e) {
+                    log.warn("解锁失败!lockKey:{} err:{}", lockKey, e.getMessage());
+                }
+            }
+        }
+    }
+
     /**
      * 获取某考生的 已完成预约次数缓存(查数据库)
      */