ApplyTaskCacheService.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. package com.qmth.exam.reserve.cache.impl;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.qmth.boot.core.concurrent.service.ConcurrentService;
  4. import com.qmth.exam.reserve.bean.apply.ApplyRecordCacheBean;
  5. import com.qmth.exam.reserve.bean.applytask.CurrentApplyTaskVO;
  6. import com.qmth.exam.reserve.bean.examsite.ExamSiteCapacityInfo;
  7. import com.qmth.exam.reserve.cache.CacheConstants;
  8. import com.qmth.exam.reserve.cache.RedisClient;
  9. import com.qmth.exam.reserve.entity.StudentApplyEntity;
  10. import com.qmth.exam.reserve.entity.TimePeriodEntity;
  11. import com.qmth.exam.reserve.service.*;
  12. import org.apache.commons.collections4.CollectionUtils;
  13. import org.apache.commons.collections4.MapUtils;
  14. import org.redisson.api.RAtomicLong;
  15. import org.redisson.api.RQueue;
  16. import org.slf4j.Logger;
  17. import org.slf4j.LoggerFactory;
  18. import org.springframework.beans.factory.annotation.Autowired;
  19. import org.springframework.data.redis.core.script.DefaultRedisScript;
  20. import org.springframework.stereotype.Component;
  21. import java.util.*;
  22. import java.util.concurrent.TimeUnit;
  23. import java.util.concurrent.locks.Lock;
  24. @Component
  25. public class ApplyTaskCacheService implements CacheConstants {
  26. private static final Logger log = LoggerFactory.getLogger(ApplyTaskCacheService.class);
  27. @Autowired
  28. private RedisClient redisClient;
  29. @Autowired
  30. private ApplyTaskService applyTaskService;
  31. @Autowired
  32. private ExamSiteService examSiteService;
  33. @Autowired
  34. private TimePeriodService timePeriodService;
  35. @Autowired
  36. private StudentService studentService;
  37. @Autowired
  38. private StudentApplyService studentApplyService;
  39. @Autowired
  40. private ConcurrentService concurrentService;
  41. /**
  42. * 获取当前启用的预约任务缓存
  43. */
  44. public CurrentApplyTaskVO currentApplyTask(Long orgId) {
  45. String cacheKey = String.format(CACHE_CURRENT_APPLY_TASK, orgId);
  46. CurrentApplyTaskVO value = redisClient.get(cacheKey, CurrentApplyTaskVO.class);
  47. if (value != null) {
  48. return value;
  49. }
  50. value = applyTaskService.currentApplyTask(orgId);
  51. if (value == null) {
  52. return null;
  53. }
  54. redisClient.set(cacheKey, value, CACHE_TIME_OUT_10, TimeUnit.MINUTES);
  55. log.info("SET cacheKey:{} curApplyTaskId:{}", cacheKey, value.getTaskId());
  56. return value;
  57. }
  58. /**
  59. * 清除当前启用的预约任务缓存
  60. */
  61. public void clearCurrentApplyTaskCache(Long orgId) {
  62. String cacheKey = String.format(CACHE_CURRENT_APPLY_TASK, orgId);
  63. redisClient.delete(cacheKey);
  64. log.warn("DELETE cacheKey:{}", cacheKey);
  65. }
  66. /**
  67. * 获取某考生的“允许预约时段次数”缓存
  68. */
  69. public int getStudentApplyNumber(Long studentId) {
  70. String cacheKey = String.format(CACHE_STUDENT_APPLY_NUMBER, studentId);
  71. Integer value = redisClient.get(cacheKey, Integer.class);
  72. if (value != null) {
  73. return value;
  74. }
  75. value = studentService.findStudentApplyNumberById(studentId);
  76. redisClient.set(cacheKey, value, CACHE_TIME_OUT_10, TimeUnit.MINUTES);
  77. log.info("SET cacheKey:{} value:{}", cacheKey, value);
  78. return value;
  79. }
  80. /**
  81. * 清除某考生的“允许预约时段次数”缓存
  82. */
  83. public void clearStudentApplyNumberCache(Long studentId) {
  84. String cacheKey = String.format(CACHE_STUDENT_APPLY_NUMBER, studentId);
  85. redisClient.delete(cacheKey);
  86. log.warn("DELETE cacheKey:{}", cacheKey);
  87. }
  88. /**
  89. * 获取某考点某时段的“剩余可约数量”缓存
  90. */
  91. public int getApplyAvailableCount(Long examSiteId, Long timePeriodId) {
  92. String cacheKey = String.format(CACHE_APPLY_AVAILABLE_COUNT, examSiteId, timePeriodId);
  93. RAtomicLong atomic = redisClient.getRedissonClient().getAtomicLong(cacheKey);
  94. return (int) atomic.get();
  95. }
  96. /**
  97. * 累加 某考点某时段的“剩余可约数量”缓存
  98. */
  99. public void increaseApplyAvailableCount(Long examSiteId, Long timePeriodId) {
  100. String cacheKey = String.format(CACHE_APPLY_AVAILABLE_COUNT, examSiteId, timePeriodId);
  101. RAtomicLong atomic = redisClient.getRedissonClient().getAtomicLong(cacheKey);
  102. long value = atomic.incrementAndGet();
  103. log.warn("累加成功,最新考点剩余可约数量:{} cacheKey:{}", value, cacheKey);
  104. }
  105. /**
  106. * 累减 某考点某时段的“剩余可约数量”缓存
  107. */
  108. public boolean decreaseApplyAvailableCount(Long examSiteId, Long timePeriodId) {
  109. String cacheKey = String.format(CACHE_APPLY_AVAILABLE_COUNT, examSiteId, timePeriodId);
  110. StringBuilder luaScript = new StringBuilder();
  111. luaScript.append("local key = KEYS[1];");
  112. luaScript.append("if (redis.call('exists', key) == 1) then");
  113. luaScript.append(" local stock = tonumber(redis.call('get', key));");
  114. luaScript.append(" local amount = tonumber(ARGV[1]);");
  115. luaScript.append(" if (stock >= amount) then");
  116. luaScript.append(" return redis.call('decrby', key, amount);");
  117. luaScript.append(" end;");
  118. luaScript.append(" return -1;");
  119. luaScript.append("end;");
  120. luaScript.append("return -2;");
  121. List<String> keys = Collections.singletonList(cacheKey);
  122. Object[] args = new Object[]{1};
  123. // 执行Lua脚本,传入键列表和参数列表
  124. DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(luaScript.toString(), Long.class);
  125. Long result = redisClient.getRedisTemplate().execute(redisScript, keys, args);
  126. Objects.requireNonNull(result, "缓存操作异常,返回结果为空!");
  127. if (-2 == result) {
  128. log.warn("扣减失败,考点剩余可约数量缓存不存在!cacheKey:{}", cacheKey);
  129. return false;
  130. } else if (-1 == result) {
  131. log.warn("扣减失败,考点剩余可约数量为0不足!cacheKey:{}", cacheKey);
  132. return false;
  133. }
  134. log.info("扣减成功,最新考点剩余可约数量:{} cacheKey:{}", result, cacheKey);
  135. return true;
  136. }
  137. /**
  138. * 刷新 某考点某时段的“剩余可约数量”缓存
  139. */
  140. public void refreshApplyAvailableCountCache(Long examSiteId, int oldCapacity, int newCapacity) {
  141. String lockKey = String.format(CacheConstants.LOCK_EXAM_SITE_CAPACITY, examSiteId);
  142. Lock lock = concurrentService.getLock(lockKey);
  143. try {
  144. if (!lock.tryLock()) {
  145. throw new RuntimeException("获取锁失败,不允许同时操作!" + lockKey);
  146. }
  147. // 获取所有时段ID集合
  148. List<TimePeriodEntity> timePeriods = timePeriodService.list(new LambdaQueryWrapper<TimePeriodEntity>().select(TimePeriodEntity::getId));
  149. if (CollectionUtils.isEmpty(timePeriods)) {
  150. return;
  151. }
  152. // 新、旧考点容量差额
  153. int diffCapacity = newCapacity - oldCapacity;
  154. for (TimePeriodEntity timePeriod : timePeriods) {
  155. String cacheKey = String.format(CACHE_APPLY_AVAILABLE_COUNT, examSiteId, timePeriod.getId());
  156. if (redisClient.exist(cacheKey)) {
  157. if (diffCapacity == 0) {
  158. // 考点总容量未变化,不用更新缓存
  159. continue;
  160. }
  161. // 总容量变化时,则更新考点剩余可约数量缓存
  162. RAtomicLong atomic = redisClient.getRedissonClient().getAtomicLong(cacheKey);
  163. long availableCount = Math.max(atomic.get() + diffCapacity, 0);
  164. atomic.set(availableCount);
  165. log.warn("SET cacheKey:{} value:{}", cacheKey, availableCount);
  166. } else {
  167. // 初始考点剩余可约数量缓存
  168. RAtomicLong atomic = redisClient.getRedissonClient().getAtomicLong(cacheKey);
  169. atomic.set(newCapacity);
  170. log.info("SET cacheKey:{} value:{}", cacheKey, newCapacity);
  171. }
  172. }
  173. } finally {
  174. try {
  175. lock.unlock();
  176. } catch (Exception e) {
  177. log.warn("解锁失败!lockKey:{} err:{}", lockKey, e.getMessage());
  178. }
  179. }
  180. }
  181. /**
  182. * 初始或重置计算 所有考点所有时段的“剩余可约数量”缓存
  183. */
  184. public void initApplyAvailableCountCacheForAllExamSites(boolean skipExisted) {
  185. // 获取所有考点和考点总容量集合
  186. List<ExamSiteCapacityInfo> examSites = examSiteService.findAllExamSiteCapacityList();
  187. if (CollectionUtils.isEmpty(examSites)) {
  188. return;
  189. }
  190. // 获取所有时段ID集合
  191. List<TimePeriodEntity> timePeriods = timePeriodService.list(new LambdaQueryWrapper<TimePeriodEntity>().select(TimePeriodEntity::getId));
  192. if (CollectionUtils.isEmpty(timePeriods)) {
  193. return;
  194. }
  195. for (ExamSiteCapacityInfo examSite : examSites) {
  196. String lockKey = String.format(CacheConstants.LOCK_EXAM_SITE_CAPACITY, examSite.getExamSiteId());
  197. Lock lock = concurrentService.getLock(lockKey);
  198. try {
  199. if (!lock.tryLock()) {
  200. log.warn("获取锁失败,不允许同时操作!{}", lockKey);
  201. return;
  202. }
  203. for (TimePeriodEntity timePeriod : timePeriods) {
  204. String cacheKey = String.format(CACHE_APPLY_AVAILABLE_COUNT, examSite.getExamSiteId(), timePeriod.getId());
  205. if (redisClient.exist(cacheKey) && skipExisted) {
  206. // 跳过存在的缓存
  207. continue;
  208. }
  209. // 获取某考点某时段的“已预约数量”(仅查数据库会有误差,需等预约队列中全部完成数据库持久化后再执行!)
  210. int finishCount = studentApplyService.countApplyFinishForExamSiteAndTimePeriod(examSite.getExamSiteId(), timePeriod.getId());
  211. // 剩余可约数量
  212. int availableCount = Math.max(examSite.getCapacity() - finishCount, 0);
  213. RAtomicLong atomic = redisClient.getRedissonClient().getAtomicLong(cacheKey);
  214. atomic.set(availableCount);
  215. log.warn("SET cacheKey:{} value:{}", cacheKey, availableCount);
  216. }
  217. } finally {
  218. try {
  219. lock.unlock();
  220. } catch (Exception e) {
  221. log.warn("解锁失败!lockKey:{} err:{}", lockKey, e.getMessage());
  222. }
  223. }
  224. }
  225. }
  226. /**
  227. * 获取某考生的 已完成预约次数缓存(查数据库)
  228. */
  229. public int getStudentApplyFinishCountFromDB(Long studentId) {
  230. LambdaQueryWrapper<StudentApplyEntity> wrapper = new LambdaQueryWrapper<>();
  231. wrapper.eq(StudentApplyEntity::getStudentId, studentId);
  232. wrapper.eq(StudentApplyEntity::getCancel, Boolean.FALSE);
  233. return studentApplyService.count(wrapper);
  234. }
  235. /**
  236. * 获取某考生的 已完成预约次数缓存
  237. */
  238. public int getStudentApplyFinishCount(Long studentId) {
  239. Map<String, ApplyRecordCacheBean> maps = this.getStudentApplyRecords(studentId);
  240. int studentApplyFinishCount = 0;
  241. for (ApplyRecordCacheBean bean : maps.values()) {
  242. if (!bean.getCancel()) {
  243. studentApplyFinishCount++;
  244. }
  245. }
  246. return studentApplyFinishCount;
  247. }
  248. /**
  249. * 获取某考生的 所有的“预约记录”缓存
  250. */
  251. public Map<String, ApplyRecordCacheBean> getStudentApplyRecords(Long studentId) {
  252. String cacheKey = String.format(CACHE_STUDENT_APPLY_RECORD, studentId);
  253. if (!redisClient.exist(cacheKey)) {
  254. Map<String, ApplyRecordCacheBean> maps = this.getStudentApplyRecordsFromDB(studentId);
  255. if (MapUtils.isEmpty(maps)) {
  256. return new HashMap<>();
  257. }
  258. for (ApplyRecordCacheBean bean : maps.values()) {
  259. this.saveStudentApplyRecord(bean);
  260. }
  261. redisClient.expire(cacheKey, CACHE_TIME_OUT_30, TimeUnit.DAYS);
  262. return maps;
  263. }
  264. return redisClient.getEntriesForHash(cacheKey, ApplyRecordCacheBean.class);
  265. }
  266. /**
  267. * 获取某考生的 所有的“预约记录”(查数据库)
  268. */
  269. public Map<String, ApplyRecordCacheBean> getStudentApplyRecordsFromDB(Long studentId) {
  270. LambdaQueryWrapper<StudentApplyEntity> wrapper = new LambdaQueryWrapper<>();
  271. wrapper.eq(StudentApplyEntity::getStudentId, studentId);
  272. List<StudentApplyEntity> list = studentApplyService.list(wrapper);
  273. if (CollectionUtils.isEmpty(list)) {
  274. return new HashMap<>();
  275. }
  276. Map<String, ApplyRecordCacheBean> maps = new HashMap<>();
  277. for (StudentApplyEntity entity : list) {
  278. ApplyRecordCacheBean bean = new ApplyRecordCacheBean();
  279. bean.setStudentId(entity.getStudentId());
  280. bean.setExamSiteId(entity.getExamSiteId());
  281. bean.setTimePeriodId(entity.getTimePeriodId());
  282. bean.setCancel(entity.getCancel());
  283. bean.setOperateId(entity.getOperateId());
  284. bean.setOperateTime(entity.getUpdateTime());
  285. String hashKey = String.format("%s_%s", entity.getExamSiteId(), entity.getTimePeriodId());
  286. maps.put(hashKey, bean);
  287. }
  288. return maps;
  289. }
  290. /**
  291. * 获取某考生的 某考点某时段的“预约记录”缓存
  292. */
  293. public ApplyRecordCacheBean getStudentApplyRecord(Long studentId, Long examSiteId, Long timePeriodId) {
  294. String cacheKey = String.format(CACHE_STUDENT_APPLY_RECORD, studentId);
  295. String hashKey = String.format("%s_%s", examSiteId, timePeriodId);
  296. ApplyRecordCacheBean cacheBean = redisClient.getForHash(cacheKey, hashKey, ApplyRecordCacheBean.class);
  297. if (cacheBean != null) {
  298. return cacheBean;
  299. }
  300. // 缓存不存在时,从数据库再查一次
  301. StudentApplyEntity entity = this.getStudentApplyRecordFormDB(studentId, examSiteId, timePeriodId);
  302. if (entity != null) {
  303. cacheBean = new ApplyRecordCacheBean();
  304. cacheBean.setStudentId(entity.getStudentId());
  305. cacheBean.setExamSiteId(entity.getExamSiteId());
  306. cacheBean.setTimePeriodId(entity.getTimePeriodId());
  307. cacheBean.setCancel(entity.getCancel());
  308. cacheBean.setOperateId(entity.getOperateId());
  309. cacheBean.setOperateTime(entity.getUpdateTime());
  310. return cacheBean;
  311. }
  312. return null;
  313. }
  314. /**
  315. * 获取某考生的 某考点某时段的“预约记录”(查数据库)
  316. */
  317. public StudentApplyEntity getStudentApplyRecordFormDB(Long studentId, Long examSiteId, Long timePeriodId) {
  318. LambdaQueryWrapper<StudentApplyEntity> wrapper = new LambdaQueryWrapper<>();
  319. wrapper.eq(StudentApplyEntity::getExamSiteId, examSiteId);
  320. wrapper.eq(StudentApplyEntity::getTimePeriodId, timePeriodId);
  321. wrapper.eq(StudentApplyEntity::getStudentId, studentId);
  322. return studentApplyService.getOne(wrapper);
  323. }
  324. /**
  325. * 保存某考生的 某考点某时段的“预约记录”缓存
  326. */
  327. public void saveStudentApplyRecord(ApplyRecordCacheBean value) {
  328. String cacheKey = String.format(CACHE_STUDENT_APPLY_RECORD, value.getStudentId());
  329. String hashKey = String.format("%s_%s", value.getExamSiteId(), value.getTimePeriodId());
  330. redisClient.setForHash(cacheKey, hashKey, value);
  331. log.info("SET cacheKey:{} hashKey:{} cancel:{}", cacheKey, hashKey, value.getCancel());
  332. }
  333. /**
  334. * 推送至考生预约记录队列
  335. */
  336. public void pushStudentApplyRecordQueue(ApplyRecordCacheBean value) {
  337. if (value == null) {
  338. return;
  339. }
  340. RQueue<ApplyRecordCacheBean> queue = redisClient.getRedissonClient()
  341. .getQueue(QUEUE_STUDENT_APPLY_RECORD);
  342. boolean success = queue.offer(value);
  343. log.info("{}_{}_{}_{} offerQueue:{}", value.getStudentId(), value.getExamSiteId(),
  344. value.getTimePeriodId(), value.getCancel(), success);
  345. if (!success) {
  346. throw new RuntimeException("推送至考生预约记录队列失败");
  347. }
  348. }
  349. }