java 如何设置缓存
设置缓存的基本方法
在Java中设置缓存可以通过多种方式实现,包括使用内置的集合类、第三方缓存库或框架。以下是几种常见的方法:
使用ConcurrentHashMap实现简单缓存
import java.util.concurrent.ConcurrentHashMap;
public class SimpleCache<K, V> {
private final ConcurrentHashMap<K, V> cache = new ConcurrentHashMap<>();
public void put(K key, V value) {
cache.put(key, value);
}
public V get(K key) {
return cache.get(key);
}
public void remove(K key) {
cache.remove(key);
}
}
使用Guava Cache Google Guava库提供了强大的缓存功能,支持过期策略、最大容量限制等:
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
public class GuavaCacheExample {
public static void main(String[] args) {
Cache<String, String> cache = CacheBuilder.newBuilder()
.maximumSize(100) // 最大缓存条目数
.expireAfterWrite(10, TimeUnit.MINUTES) // 写入后10分钟过期
.build();
cache.put("key1", "value1");
String value = cache.getIfPresent("key1");
}
}
使用Spring Cache抽象
Spring框架提供了缓存抽象,可以方便地与多种缓存实现集成:
启用Spring缓存
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public CacheManager cacheManager() {
return new ConcurrentMapCacheManager("products");
}
}
在方法上使用缓存注解
@Service
public class ProductService {
@Cacheable("products")
public Product getProductById(String id) {
// 模拟数据库查询
return findProductInDatabase(id);
}
@CacheEvict("products")
public void refreshProduct(String id) {
// 清除缓存
}
}
使用Ehcache
Ehcache是一个广泛使用的Java缓存库:
配置Ehcache
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd">
<cache name="products"
maxEntriesLocalHeap="1000"
timeToLiveSeconds="3600"/>
</ehcache>
Java代码中使用Ehcache
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
public class EhcacheExample {
public static void main(String[] args) {
CacheManager cacheManager = CacheManager.newInstance();
Cache cache = cacheManager.getCache("products");
Element element = new Element("key1", "value1");
cache.put(element);
Element cached = cache.get("key1");
}
}
使用Redis作为分布式缓存
对于分布式系统,可以使用Redis作为缓存:
Spring Boot集成Redis

@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return template;
}
}
@Service
public class ProductService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public void cacheProduct(String id, Product product) {
redisTemplate.opsForValue().set(id, product);
}
public Product getCachedProduct(String id) {
return (Product) redisTemplate.opsForValue().get(id);
}
}
缓存策略考虑因素
- 过期时间:设置合理的缓存过期时间,避免数据过时
- 缓存大小:限制缓存大小防止内存溢出
- 淘汰策略:LRU(最近最少使用)或FIFO(先进先出)等
- 线程安全:确保缓存在多线程环境下安全访问
- 持久化:考虑是否需要将缓存持久化到磁盘
选择哪种缓存实现取决于具体需求,简单场景可以使用内存缓存,分布式系统则需要考虑Redis等分布式缓存解决方案。






