瀏覽代碼

优化统计数据缓存逻辑

ximinghao 10 月之前
父節點
當前提交
3cdfde0eb5

+ 1 - 1
src/main/java/com/skyversation/xjcy/controller/XjcyController.java

@@ -76,7 +76,7 @@ public class XjcyController {
 
     @RequestMapping(value = "/recount", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
     public String reCount() {
-        new Thread(() -> dataCountService.count());
+        new Thread(() -> dataCountService.count(System.currentTimeMillis())).start();
         return MessageManage.getInstance().getResultContent(200, "已开始重新统计", "已开始重新统计");
     }
 

+ 35 - 7
src/main/java/com/skyversation/xjcy/service/DataCountService.java

@@ -17,6 +17,8 @@ import javax.annotation.PostConstruct;
 import javax.annotation.Resource;
 import java.math.BigDecimal;
 import java.util.*;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
 import java.util.stream.Collectors;
 
 @Service
@@ -44,6 +46,37 @@ public class DataCountService {
     MultiValueMap<String, IndustrialPark> buildMap = new LinkedMultiValueMap<>();
     List<IndustrialPark> allPark = new ArrayList<>();
 
+    //简单限制统计频率
+    private static final long INTERVAL_MILLIS = 250;
+
+    private final AtomicLong lastStartTime = new AtomicLong(0);
+
+    private final AtomicBoolean running = new AtomicBoolean(false);
+
+    @PostConstruct
+    public void tryCount() {
+        long now = System.currentTimeMillis();
+        long last = lastStartTime.get();
+
+        if (now - last < INTERVAL_MILLIS) {
+            return;
+        }
+
+        if (!running.compareAndSet(false, true)) {
+            return;
+        }
+
+        if (now - lastStartTime.get() < INTERVAL_MILLIS) {
+            running.set(false);
+            return;
+        }
+
+        try {
+            count(now);
+        } finally {
+            running.set(false);
+        }
+    }
     @NoArgsConstructor
     private static class EnterpriseEconomicCount{
         BigDecimal tax = BigDecimal.ZERO;
@@ -58,8 +91,8 @@ public class DataCountService {
         }
     }
 
-    @PostConstruct
-    public void count() {
+    public void count(long startTime) {
+        lastStartTime.set(startTime);
         tempCacheTownData = new JSONObject();
         tempCacheParkData = new HashMap<>();
         tempCacheBuildData = new HashMap<>();
@@ -411,11 +444,6 @@ public class DataCountService {
     }
 
 
-    public void tryCount() {
-        if (!counted) {
-            count();
-        }
-    }
 
     public JSONObject getTownData() {
         tryCount();