浅谈Java之内存缓存
一、基本介绍
在Java中,内存缓存可以通过多种方式实现,其中最常见的是使用java.util.Map
或者使用专门的缓存库,如Google的Guava Cache或者Caffeine。
二、简单示例
使用java.util.Map
这是最直接的方法,使用Java标准库中的Map
接口来实现简单的内存缓存。
import java.util.concurrent.ConcurrentHashMap;
import java.util.Map;public class SimpleCache<K, V> {private final Map<K, V> cache = new ConcurrentHashMap<>();public V get(K key) {return cache.get(key);}public void put(K key, V value) {cache.put(key, value);}public void remove(K key) {cache.remove(key);}
}
使用Guava Cache
Guava Cache是Google Guava库的一部分,它提供了一个简单而强大的缓存实现。
首先,你需要添加Guava库到你的项目中。如果你使用Maven,可以在pom.xml
中添加以下依赖:
<dependency><groupId>com.google.guava</groupId><artifactId>guava</artifactId><version>31.0.1-jre</version> <!-- 使用最新的版本 -->
</dependency>
然后,你可以这样使用Guava Cache:
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;import java.util.concurrent.TimeUnit;public class GuavaCacheExample {private LoadingCache<String, String> cache = CacheBuilder.newBuilder().expireAfterWrite(10, TimeUnit.MINUTES) // 设置写入10分钟后过期.build(new CacheLoader<String, String>() {public String load(String key) throws Exception {return someDatabase.get(key); // 从数据库加载数据}});public String get(String key) throws Exception {return cache.get(key); // 从缓存中获取数据,如果不存在则从数据库加载}
}
使用Caffeine
Caffeine是一个高性能的Java缓存库,它提供了丰富的缓存策略和近缓存(Near Cache)等功能。
首先,添加Caffeine库到你的项目中。如果你使用Maven,可以在pom.xml
中添加以下依赖:
<dependency><groupId>com.github.ben-manes.caffeine</groupId><artifactId>caffeine</artifactId><version>2.9.3</version> <!-- 使用最新的版本 -->
</dependency>
然后,你可以这样使用Caffeine:
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cacheLoadingCache;public class CaffeineCacheExample {private LoadingCache<String, String> cache = Caffeine.newBuilder().expireAfterWrite(10, TimeUnit.MINUTES) // 设置写入10分钟后过期.build(key -> someDatabase.get(key)); // 从数据库加载数据public String get(String key) {return cache.get(key); // 从缓存中获取数据,如果不存在则从数据库加载}
}