在程序中,缓存是一个高速数据存储层,其中存储了数据子集,且一般是短暂性存储,这样往后再次请求此数据时,速度要比访问数据的主存储位置快。经过缓存,能够高效地重用以前检索或计算的数据。java
在Java应用中,对于访问频率高,更新少的数据,一般的方案是将这类数据加入缓存中,相对从数据库中读取,读缓存效率会有很大提高。数据库
在集群环境下,经常使用的分布式缓存有Redis、Memcached等。但在某些业务场景上,可能不须要去搭建一套复杂的分布式缓存系统,在单机环境下,一般是会但愿使用内部的缓存(LocalCache)。缓存
使用Map来实现一个简单的缓存功能安全
MapCacheDemo.java数据结构
package me.xueyao.cache.java; import java.lang.ref.SoftReference; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; /** * @author simon * 用map实现一个简单的缓存功能 */ public class MapCacheDemo { /** * 使用 ConcurrentHashMap,线程安全的要求。 * 我使用SoftReference <Object> 做为映射值,由于软引用能够保证在抛出OutOfMemory以前,若是缺乏内存,将删除引用的对象。 * 在构造函数中,我建立了一个守护程序线程,每5秒扫描一次并清理过时的对象。 */ private static final int CLEAN_UP_PERIOD_IN_SEC = 5; private final ConcurrentHashMap<String, SoftReference<CacheObject>> cache = new ConcurrentHashMap<>(); public MapCacheDemo() { Thread cleanerThread = new Thread(() -> { while (!Thread.currentThread().isInterrupted()) { try { Thread.sleep(CLEAN_UP_PERIOD_IN_SEC * 1000); cache.entrySet().removeIf(entry -> Optional.ofNullable(entry.getValue()) .map(SoftReference::get) .map(CacheObject::isExpired) .orElse(false)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }); cleanerThread.setDaemon(true); cleanerThread.start(); } public void add(String key, Object value, long periodInMillis) { if (key == null) { return; } if (value == null) { cache.remove(key); } else { long expiryTime = System.currentTimeMillis() + periodInMillis; cache.put(key, new SoftReference<>(new CacheObject(value, expiryTime))); } } public void remove(String key) { cache.remove(key); } public Object get(String key) { return Optional.ofNullable(cache.get(key)).map(SoftReference::get).filter(cacheObject -> !cacheObject.isExpired()).map(CacheObject::getValue).orElse(null); } public void clear() { cache.clear(); } public long size() { return cache.entrySet().stream().filter(entry -> Optional.ofNullable(entry.getValue()).map(SoftReference::get).map(cacheObject -> !cacheObject.isExpired()).orElse(false)).count(); } /** * 缓存对象value */ private static class CacheObject { private Object value; private long expiryTime; private CacheObject(Object value, long expiryTime) { this.value = value; this.expiryTime = expiryTime; } boolean isExpired() { return System.currentTimeMillis() > expiryTime; } public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } } }
代码测试类MapCacheDemoTests.java分布式
package me.xueyao.cache.java; public class MapCacheDemoTests { public static void main(String[] args) throws InterruptedException { MapCacheDemo mapCacheDemo = new MapCacheDemo(); mapCacheDemo.add("uid_10001", "{1}", 5 * 1000); mapCacheDemo.add("uid_10002", "{2}", 5 * 1000); mapCacheDemo.add("uid_10003", "{3}", 5 * 1000); System.out.println("从缓存中取出值:" + mapCacheDemo.get("uid_10001")); Thread.sleep(5000L); System.out.println("5秒钟事后"); System.out.println("从缓存中取出值:" + mapCacheDemo.get("uid_10001")); // 5秒后数据自动清除了~ } }