java cache
- IT科技
- 關注:1.79W次
<link rel="stylesheet" href="https://js.how234.com/third-party/SyntaxHighlighter/shCoreDefault.css" type="text/css" /><script type="text/javascript" src="https://js.how234.com/third-party/SyntaxHighlighter/shCore.js"></script><script type="text/javascript"> SyntaxHighlighter.all(); </script>
cache java是什麼, 讓我們一起了解一下?
Cache 是一個像 Map 一樣的數據結構,它允許基於 Key 的臨時儲存。快取被單個 CacheManager 擁有。
Java 的快取 API 定義了五個核心接口:CachingProvider,CacheManager,Cache,Entry 和 ExpiryPolicy。
Java實現cache的基本機制是什麼?
我這裏說的cache不是指CPU和RAM之間的快取,而是java應用中間常用的快取。最常使用的場合就是訪問數據庫的時候爲了提高效率而使用的 cache。一般的用法就是把數據從數據庫讀到內存,然後之後的數據訪問都從內存來讀,從而減少對數據庫的讀取次數來提高效率。
說了這麼多,Java 下到底如何實現Cache,希望下面的實際案例可以幫助到你。
public class CacheFactory { private static ConcurrentHashMap<String, Cache> caches = new ConcurrentHashMap<>(); private static ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1); private static void register(Cache cache) { caches.put(cache.category(), cache); } private static void registerAll() { register(new StockCache()); } public static void init() { registerAll(); for (Cache cache : caches.values()) { executorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { cache.refresh(); } }, 0, cache.interval(), TimeUnit.MILLISECONDS); } } public static Cache getCache(String key) { if (caches.contains(key)) { return caches.get(key); } return null; }} // cache接口除了需要提供interval和refresh以外,還需要提供一個category來區分不同的Cachepublic interface Cache { /** * Refresh the cache. If succeed, return true, else return false; * * @return */ boolean refresh(); /** * How much time it will refresh the cache. * * @return */ long interval(); /** * Cache's category. Each cache has distinct category. * * @return */ String category();}
- 文章版權屬於文章作者所有,轉載請註明 https://shqsg.com/zh-hant/dianzi/qkgw1o.html