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