CacheManager.java 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package com.gzlh.weighbridge.server;
  2. import cn.hutool.cache.CacheUtil;
  3. import cn.hutool.cache.impl.TimedCache;
  4. import cn.hutool.core.thread.ThreadUtil;
  5. import cn.hutool.json.JSONUtil;
  6. import cn.hutool.log.StaticLog;
  7. import com.gzlh.task.CleanTask;
  8. import java.util.Comparator;
  9. import java.util.Map;
  10. import java.util.Optional;
  11. import java.util.concurrent.ConcurrentHashMap;
  12. public class CacheManager {
  13. private final static Map<Integer, Integer> WEIGHT_COUNT_CACHE = new ConcurrentHashMap<>(1024);
  14. public final static TimedCache<String, Boolean> STOP_MAP = CacheUtil.newTimedCache(180000);
  15. //30秒清除一次
  16. private final static TimedCache<String, Integer> CLEAN_REQ_CACHE = CacheUtil.newTimedCache(30000);
  17. private static final String FLAG = "flag";
  18. public static void add(int weight) {
  19. Boolean stop = STOP_MAP.get(FLAG, false);
  20. if (stop != null && stop && !WEIGHT_COUNT_CACHE.isEmpty()) {
  21. return;
  22. }
  23. Integer count = WEIGHT_COUNT_CACHE.get(weight);
  24. if (count == null) {
  25. count = 0;
  26. }
  27. count++;
  28. WEIGHT_COUNT_CACHE.put(weight, count);
  29. }
  30. public static Integer getMaxCountWeight() {
  31. Boolean stop = STOP_MAP.get(FLAG, false);
  32. if (stop != null && stop) {
  33. return -1;
  34. }
  35. Optional<Map.Entry<Integer, Integer>> optional = WEIGHT_COUNT_CACHE.entrySet().stream().max(Comparator.comparingInt(Map.Entry::getValue));
  36. if (optional.isPresent()) {
  37. Map.Entry<Integer, Integer> entry = optional.get();
  38. //某个磅数达到了80次
  39. if (entry.getValue() > 40) {
  40. STOP_MAP.put(FLAG, true);
  41. return entry.getKey();
  42. }
  43. }
  44. return -1;
  45. }
  46. public static Integer getWeight() {
  47. StaticLog.info("list:{}", JSONUtil.toJsonStr(WEIGHT_COUNT_CACHE));
  48. Optional<Map.Entry<Integer, Integer>> optional = WEIGHT_COUNT_CACHE.entrySet().stream().max(Comparator.comparingInt(Map.Entry::getValue));
  49. if (optional.isPresent()) {
  50. Map.Entry<Integer, Integer> entry = optional.get();
  51. //某个磅数达到了80次
  52. if (entry.getValue() > 40) {
  53. STOP_MAP.put(FLAG, true);
  54. return entry.getKey();
  55. }
  56. }
  57. return -1;
  58. }
  59. /**
  60. * 清除缓存数据
  61. *
  62. * @param channel
  63. * @param serverUrl
  64. */
  65. public static void clean(String channel, String serverUrl) {
  66. STOP_MAP.put(FLAG, false);
  67. WEIGHT_COUNT_CACHE.clear();
  68. Integer flag = CLEAN_REQ_CACHE.get(FLAG, false);
  69. if (flag == null || flag == 0) {
  70. CLEAN_REQ_CACHE.put(FLAG, 1);
  71. ThreadUtil.execute(new CleanTask(serverUrl, channel));
  72. }
  73. }
  74. }