java 如何使用缓存
缓存的基本概念
缓存是一种临时存储数据的技术,用于提高数据访问速度,减少对数据库或其他慢速存储的重复访问。在Java中,缓存通常用于存储频繁访问的数据,例如数据库查询结果、计算结果或API响应。
使用Java内置缓存
Java提供了简单的缓存实现,例如HashMap或ConcurrentHashMap,适合小型应用或临时缓存需求。
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class SimpleCache {
private static final Map<String, Object> cache = new ConcurrentHashMap<>();
public static void put(String key, Object value) {
cache.put(key, value);
}
public static Object get(String key) {
return cache.get(key);
}
public static void remove(String key) {
cache.remove(key);
}
}
使用第三方缓存库
对于更复杂的缓存需求,可以使用成熟的第三方缓存库,例如Ehcache、Caffeine或Guava Cache。
Caffeine缓存示例
Caffeine是一个高性能的Java缓存库,支持自动过期、大小限制等功能。
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import java.util.concurrent.TimeUnit;
public class CaffeineCacheExample {
private static final Cache<String, String> cache = Caffeine.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES) // 写入后10分钟过期
.maximumSize(100) // 最大缓存条目数
.build();
public static void put(String key, String value) {
cache.put(key, value);
}
public static String get(String key) {
return cache.getIfPresent(key);
}
}
Ehcache缓存示例
Ehcache是一个广泛使用的缓存框架,支持分布式缓存和持久化存储。

import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
public class EhcacheExample {
private static CacheManager cacheManager;
private static Cache<String, String> cache;
static {
cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build();
cacheManager.init();
cache = cacheManager.createCache("myCache",
CacheConfigurationBuilder.newCacheConfigurationBuilder(
String.class, String.class,
ResourcePoolsBuilder.heap(100) // 最大缓存条目数
));
}
public static void put(String key, String value) {
cache.put(key, value);
}
public static String get(String key) {
return cache.get(key);
}
}
使用Spring Cache抽象
Spring框架提供了缓存抽象,支持多种缓存实现(如Caffeine、Ehcache、Redis),并通过注解简化缓存操作。
启用Spring缓存
在Spring Boot项目中,通过@EnableCaching启用缓存支持。
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableCaching
public class CacheConfig {}
使用缓存注解
@Cacheable:标记方法结果可缓存。@CacheEvict:清除缓存条目。@CachePut:更新缓存条目。
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class BookService {
@Cacheable(value = "books", key = "#isbn")
public Book findBookByIsbn(String isbn) {
// 模拟数据库查询
return new Book(isbn, "Sample Book");
}
}
分布式缓存
对于分布式系统,可以使用Redis或Memcached作为缓存中间件。Spring Boot支持通过spring-boot-starter-data-redis集成Redis缓存。

Redis缓存配置
在application.properties中配置Redis连接:
spring.redis.host=localhost
spring.redis.port=6379
使用Redis缓存
在Spring Boot中,Redis会自动作为缓存实现。
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class ProductService {
@Cacheable(value = "products", key = "#id")
public Product getProductById(String id) {
// 模拟数据库查询
return new Product(id, "Sample Product");
}
}
缓存策略优化
- 缓存失效:设置合理的过期时间(TTL),避免数据不一致。
- 缓存穿透:对不存在的键也缓存空值,防止频繁查询数据库。
- 缓存雪崩:分散缓存过期时间,避免同时失效导致数据库压力激增。
缓存监控
使用工具(如Micrometer、Prometheus)监控缓存命中率、缓存大小等指标,优化缓存性能。
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class CacheMetrics {
private final MeterRegistry meterRegistry;
@Autowired
public CacheMetrics(MeterRegistry meterRegistry) {
this.meterRegistry = meterRegistry;
}
public void recordCacheHit() {
meterRegistry.counter("cache.hits").increment();
}
}
通过以上方法,可以在Java中高效地使用缓存,提升应用性能并减少对后端存储的压力。






