123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- package com.gzlh.weighbridge.server;
- import cn.hutool.cache.CacheUtil;
- import cn.hutool.cache.impl.TimedCache;
- import cn.hutool.core.thread.ThreadUtil;
- import cn.hutool.json.JSONUtil;
- import cn.hutool.log.StaticLog;
- import com.gzlh.task.CleanTask;
- import java.util.Comparator;
- import java.util.Map;
- import java.util.Optional;
- import java.util.concurrent.ConcurrentHashMap;
- public class CacheManager {
- private final static Map<Integer, Integer> WEIGHT_COUNT_CACHE = new ConcurrentHashMap<>(1024);
- public final static TimedCache<String, Boolean> STOP_MAP = CacheUtil.newTimedCache(180000);
- //30秒清除一次
- private final static TimedCache<String, Integer> CLEAN_REQ_CACHE = CacheUtil.newTimedCache(30000);
- private static final String FLAG = "flag";
- public static void add(int weight) {
- Boolean stop = STOP_MAP.get(FLAG, false);
- if (stop != null && stop && !WEIGHT_COUNT_CACHE.isEmpty()) {
- return;
- }
- Integer count = WEIGHT_COUNT_CACHE.get(weight);
- if (count == null) {
- count = 0;
- }
- count++;
- WEIGHT_COUNT_CACHE.put(weight, count);
- }
- public static Integer getMaxCountWeight() {
- Boolean stop = STOP_MAP.get(FLAG, false);
- if (stop != null && stop) {
- return -1;
- }
- Optional<Map.Entry<Integer, Integer>> optional = WEIGHT_COUNT_CACHE.entrySet().stream().max(Comparator.comparingInt(Map.Entry::getValue));
- if (optional.isPresent()) {
- Map.Entry<Integer, Integer> entry = optional.get();
- //某个磅数达到了80次
- if (entry.getValue() > 40) {
- STOP_MAP.put(FLAG, true);
- return entry.getKey();
- }
- }
- return -1;
- }
- public static Integer getWeight() {
- StaticLog.info("list:{}", JSONUtil.toJsonStr(WEIGHT_COUNT_CACHE));
- Optional<Map.Entry<Integer, Integer>> optional = WEIGHT_COUNT_CACHE.entrySet().stream().max(Comparator.comparingInt(Map.Entry::getValue));
- if (optional.isPresent()) {
- Map.Entry<Integer, Integer> entry = optional.get();
- //某个磅数达到了80次
- if (entry.getValue() > 40) {
- STOP_MAP.put(FLAG, true);
- return entry.getKey();
- }
- }
- return -1;
- }
- /**
- * 清除缓存数据
- *
- * @param channel
- * @param serverUrl
- */
- public static void clean(String channel, String serverUrl) {
- STOP_MAP.put(FLAG, false);
- WEIGHT_COUNT_CACHE.clear();
- Integer flag = CLEAN_REQ_CACHE.get(FLAG, false);
- if (flag == null || flag == 0) {
- CLEAN_REQ_CACHE.put(FLAG, 1);
- ThreadUtil.execute(new CleanTask(serverUrl, channel));
- }
- }
- }
|