From a7e6cc0b051ac914583ab61158896236bb84d036 Mon Sep 17 00:00:00 2001 From: xiaoliuhu Date: Sat, 20 Apr 2024 19:20:05 +0800 Subject: [PATCH] =?UTF-8?q?fix:=E6=8B=93=E5=B1=95=E5=8F=AF=E8=87=AA?= =?UTF-8?q?=E5=AE=9A=E4=B9=89=E6=97=B6=E9=97=B4=E7=BC=93=E5=AD=98=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3,app=E6=8C=87=E6=95=B0=E6=8E=A5=E5=8F=A3=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0=E7=BC=93=E5=AD=981=E5=88=86=E9=92=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../stock/market/utils/RequestCacheUtils.java | 44 +++++++++++++++++++ .../stock/market/web/StockApiController.java | 2 +- 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/src/main/java/cn/stock/market/utils/RequestCacheUtils.java b/src/main/java/cn/stock/market/utils/RequestCacheUtils.java index 2d3b35f..d382264 100644 --- a/src/main/java/cn/stock/market/utils/RequestCacheUtils.java +++ b/src/main/java/cn/stock/market/utils/RequestCacheUtils.java @@ -65,6 +65,50 @@ public class RequestCacheUtils { return response; } + + /** + * 根据时间创建缓存 + * @param key key + * @param duration 时间(毫秒) + * @return + */ + public static Cache> cacheByMilliseconds(String key,long duration) { + if(! map.containsKey(key)) { + log.info("创建缓存: {}", key); + Cache> cache = CacheBuilder.newBuilder() + .maximumSize(1000) + .expireAfterWrite(duration,TimeUnit.MILLISECONDS) + .weakValues() + .recordStats() + .build( +// new CacheLoader() { +// @Override +// public Object load(String key) throws Exception { +// return func.apply(key); +// } +// } + ); + map.put(key, cache); + } + + return map.get(key); + } + + @SneakyThrows + public static ServerResponse cache(String module, String key,long duration, Function> func) { + Cache> cache = cacheByMilliseconds(module,duration); + AtomicBoolean bool = new AtomicBoolean(true); + ServerResponse response = (ServerResponse) cache.get(key, () -> { + bool.set(false); + return func.apply(key); + }); + + if(bool.get()) { + log.info("命中缓存 module: {}, key: {}, 时间戳: {}", module, key, System.currentTimeMillis()); + } + + return response; + } public static void main(String[] args) throws InterruptedException { ServerResponse response = null; diff --git a/src/main/java/cn/stock/market/web/StockApiController.java b/src/main/java/cn/stock/market/web/StockApiController.java index 7a36069..aea2683 100644 --- a/src/main/java/cn/stock/market/web/StockApiController.java +++ b/src/main/java/cn/stock/market/web/StockApiController.java @@ -238,7 +238,7 @@ public class StockApiController { @ResponseBody public ServerResponse getIndiaIndexByToday() { String INDEX_CODE = "TODAY_INDEX"; - return RequestCacheUtils.cache("getIndiaIndexByToday.do", INDEX_CODE, (string) -> { + return RequestCacheUtils.cache("getIndiaIndexByToday.do", INDEX_CODE,60000, (string) -> { return this.stockService.getIndexByBtoday(); }); }