From 63769df44b9baf8339f6e0e151f4b6908386087c Mon Sep 17 00:00:00 2001
From: dd <gitluke@outlook.com>
Date: Fri, 26 Dec 2025 11:53:32 +0800
Subject: [PATCH] 1

---
 src/main/java/com/nq/service/impl/StockServiceImpl.java |  149 +++++++++++++++++++++++++++++++++++++++----------
 1 files changed, 119 insertions(+), 30 deletions(-)

diff --git a/src/main/java/com/nq/service/impl/StockServiceImpl.java b/src/main/java/com/nq/service/impl/StockServiceImpl.java
index 09fa4f9..6567b19 100644
--- a/src/main/java/com/nq/service/impl/StockServiceImpl.java
+++ b/src/main/java/com/nq/service/impl/StockServiceImpl.java
@@ -40,6 +40,7 @@
 import java.text.SimpleDateFormat;
 import java.util.*;
 import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.locks.ReentrantLock;
 import javax.annotation.Resource;
 import javax.servlet.http.HttpServletRequest;
@@ -434,57 +435,145 @@
 
 
 
-    // 只需要缓存一个最近返回的Object
-    private static Object lastResult = null;
-    private static long lastExecuteTime = 0;
+    // 缓存键类,包含三个参数
+    private static class CacheKey {
+        private final String pid;
+        private final String interval;
+        private final String stockType;
+
+        public CacheKey(String pid, String interval, String stockType) {
+            this.pid = pid;
+            this.interval = interval;
+            this.stockType = stockType;
+        }
+
+        @Override
+        public boolean equals(Object o) {
+            if (this == o) return true;
+            if (o == null || getClass() != o.getClass()) return false;
+            CacheKey cacheKey = (CacheKey) o;
+            return pid.equals(cacheKey.pid) &&
+                    interval.equals(cacheKey.interval) &&
+                    stockType.equals(cacheKey.stockType);
+        }
+
+        @Override
+        public int hashCode() {
+            int result = pid.hashCode();
+            result = 31 * result + interval.hashCode();
+            result = 31 * result + stockType.hashCode();
+            return result;
+        }
+
+        @Override
+        public String toString() {
+            return "CacheKey{pid='" + pid + "', interval='" + interval + "', stockType='" + stockType + "'}";
+        }
+    }
+
+    // 缓存条目类
+    private static class CacheEntry {
+        Object result;
+        long lastExecuteTime;
+
+        CacheEntry(Object result, long lastExecuteTime) {
+            this.result = result;
+            this.lastExecuteTime = lastExecuteTime;
+        }
+    }
+
+    // 缓存存储:每个CacheKey对应一个CacheEntry
+    private static final Map<CacheKey, CacheEntry> cacheMap = new ConcurrentHashMap<>();
+
+    // 锁对象存储:每个CacheKey有自己的锁
+    private static final Map<CacheKey, Object> lockMap = new ConcurrentHashMap<>();
+
     private static final long MIN_INTERVAL_MS = 3000;
-    private static final Object cacheLock = new Object();
 
     @Override
     public Object getKData(String pid, String interval, String stockType) {
+        CacheKey cacheKey = new CacheKey(pid, interval, stockType);
         long currentTime = System.currentTimeMillis();
 
-        // 第一次快速检查(不加锁)
-        if (lastResult != null && (currentTime - lastExecuteTime) < MIN_INTERVAL_MS) {
-            return lastResult;
+        // 1. 快速检查缓存(无锁)
+        CacheEntry cached = cacheMap.get(cacheKey);
+        if (cached != null && (currentTime - cached.lastExecuteTime) < MIN_INTERVAL_MS) {
+            return cached.result;
         }
 
-        // 同步块内再次检查并更新
-        synchronized (cacheLock) {
+        // 2. 获取该缓存键对应的锁
+        Object keyLock = lockMap.computeIfAbsent(cacheKey, k -> new Object());
+
+        // 3. 同步块内再次检查
+        synchronized (keyLock) {
             currentTime = System.currentTimeMillis();
-            if (lastResult != null && (currentTime - lastExecuteTime) < MIN_INTERVAL_MS) {
-                return lastResult;
+            cached = cacheMap.get(cacheKey);
+
+            if (cached != null && (currentTime - cached.lastExecuteTime) < MIN_INTERVAL_MS) {
+                return cached.result;
             }
 
-            // 获取新数据
+            // 4. 获取新数据
             Object newResult = doGetKData(pid, interval, stockType);
 
-            // 更新缓存
-            lastResult = newResult;
-            lastExecuteTime = System.currentTimeMillis();
+            // 5. 更新缓存
+            if (newResult != null) {
+                cacheMap.put(cacheKey, new CacheEntry(newResult, System.currentTimeMillis()));
+                return newResult;
+            } else if (cached != null) {
+                // 请求失败,返回旧缓存
+                return cached.result;
+            }
 
-            return newResult;
+            return "{\"error\":\"获取K线数据失败\"}";
         }
     }
 
     private Object doGetKData(String pid, String interval, String stockType) {
-        EStockType eStockType = EStockType.getEStockTypeByCode(stockType);
-        Object object = HttpUtil.get(eStockType.stockUrl + "kline?pid=" + pid + "&interval=" + interval + "&key=" + eStockType.stockKey);
-        Gson gson = new Gson();
-        List<kData> dataList = gson.fromJson(object.toString(), new TypeToken<List<kData>>(){}.getType());
+        try {
+            EStockType eStockType = EStockType.getEStockTypeByCode(stockType);
+            String url = eStockType.stockUrl + "kline?pid=" + pid +
+                    "&interval=" + interval + "&key=" + eStockType.stockKey;
 
-        Stock stock = stockMapper.selectOne(new LambdaQueryWrapper<Stock>().eq(Stock::getStockCode, pid).eq(Stock::getStockType, "IN"));
-        BigDecimal nowPrice = iPriceServices.getNowPrice(stock.getStockCode());
-        Map singleStock = getSingleStock(stock.getStockCode());
-        StockVO stockVO = (StockVO)singleStock.get("stock");
+            Object object = HttpUtil.get(url);
+            Gson gson = new Gson();
+            List<kData> dataList = gson.fromJson(object.toString(),
+                    new TypeToken<List<kData>>(){}.getType());
 
-        kData lastData = dataList.get(dataList.size() - 1);
-        lastData.setC(nowPrice.toString());
-        lastData.setO(stockVO.getOpen_px());
-        lastData.setH(stockVO.getToday_max());
-        lastData.setL(stockVO.getToday_min());
+            // 补充实时数据
+            if (dataList != null && !dataList.isEmpty()) {
+                enrichWithRealTimeData(pid, dataList);
+            }
 
-        return gson.toJson(dataList);
+            return gson.toJson(dataList);
+
+        } catch (Exception e) {
+            e.printStackTrace();
+            return null; // 返回null表示失败
+        }
+    }
+
+    private void enrichWithRealTimeData(String pid, List<kData> dataList) {
+        try {
+            Stock stock = stockMapper.selectOne(new LambdaQueryWrapper<Stock>()
+                    .eq(Stock::getStockCode, pid)
+                    .eq(Stock::getStockType, "IN"));
+
+            if (stock != null) {
+                BigDecimal nowPrice = iPriceServices.getNowPrice(stock.getStockCode());
+                Map singleStock = getSingleStock(stock.getStockCode());
+                StockVO stockVO = (StockVO)singleStock.get("stock");
+
+                kData lastData = dataList.get(dataList.size() - 1);
+                lastData.setC(nowPrice.toString());
+                lastData.setO(stockVO.getOpen_px());
+                lastData.setH(stockVO.getToday_max());
+                lastData.setL(stockVO.getToday_min());
+            }
+        } catch (Exception e) {
+            // 实时数据获取失败不影响K线数据返回
+            e.printStackTrace();
+        }
     }
 
     @Override

--
Gitblit v1.9.3