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(); }); }