在Spring Boot应用中添加本地缓存是一种常见的优化手段,可以显著提升应用程序的响应时间和减少对后端数据源(如数据库)的压力。下面是一个使用Spring Boot添加本地缓存的基本步骤:
1. 添加依赖
首先,你需要在pom.xml
或build.gradle
中添加Spring Boot的缓存启动器依赖:
对于Maven:
Xml
1<dependency>
2 <groupId>org.springframework.boot</groupId>
3 <artifactId>spring-boot-starter-cache</artifactId>
4</dependency>
对于Gradle:
Groovy
implementation 'org.springframework.boot:spring-boot-starter-cache'
2. 开启缓存支持
在Spring Boot的主配置类上添加@EnableCaching
注解以启用缓存支持。
Java
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.yunjia.ntl.common.config.properties.CacheProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <p>初始化缓存管理器</p>
*
*/
@Slf4j
@EnableCaching
@Configuration
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "cache.caffeine", value = "enabled")
public class CacheConfig {
private final CacheProperties cacheProperties;
/**
* 创建基于Caffeine的Cache Manager
*/
@Bean
@Primary
public CacheManager caffeineCacheManager() {
log.debug("caffeine-plus create cacheManager");
SimpleCacheManager cacheManager = new SimpleCacheManager();
Map<String, CaffeineCache> cacheMap = new HashMap<>(2);
// 设置全局配置的本地缓存
List<String> globalCacheNames = cacheProperties.getCacheName();
if (null != globalCacheNames && !globalCacheNames.isEmpty()) {
addCacheObject(cacheMap, globalCacheNames, cacheProperties.getSpec());
}
// 设置自定义属性缓存, 可以覆盖全局缓存
List<CacheProperties.Config> configs = cacheProperties.getConfigs();
if (null != configs && !configs.isEmpty()) {
for (CacheProperties.Config config : configs) {
List<String> cacheNames = config.getCacheName();
if (null == cacheNames || cacheNames.isEmpty()) {
continue;
}
addCacheObject(cacheMap, cacheNames, config.getSpec());
}
}
// 加入到缓存管理器进行管理
cacheManager.setCaches(cacheMap.values());
return cacheManager;
}
/**
* 添加缓存对象
* 不支持refreshAfterWrite参数
* refreshAfterWrite参数需要配合cacheLoader使用,需要自定义cacheManager
*/
private void addCacheObject(Map<String, CaffeineCache> cacheMap, List<String> cacheNames, String caffeineSpec) {
for (String cacheName : cacheNames) {
/*
初始化caffeine对象
*/
Caffeine<Object, Object> caffeine = Caffeine.from(caffeineSpec).recordStats();
/*
监听缓存淘汰原因
*/
caffeine.removalListener((key, value, cause) -> log.debug("缓存键 [{}], 缓存值 [{}] 被淘汰的原因为: [{}]", key, value, cause));
/*
构建caffeine缓存
*/
Cache<Object, Object> cache = caffeine.build();
CaffeineCache caffeineCache = new CaffeineCache(cacheName, cache);
// 覆盖添加
cacheMap.put(cacheName, caffeineCache);
}
}
}
或者在你的主应用类上添加此注解。
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* <p>初始化缓存参数</p>
*/
@Data
@Component
@ConfigurationProperties(prefix = "cache.caffeine")
@ConditionalOnProperty(prefix = "cache.caffeine", value = "enabled")
public class CacheProperties {
private List<String> cacheName;
private String spec;
private List<Config> configs;
@Getter
@Setter
public static class Config {
private List<String> cacheName;
private String spec;
}
}
import cn.hutool.extra.spring.SpringUtil;
import com.github.benmanes.caffeine.cache.stats.CacheStats;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCache;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* <p>本地缓存工具类</p>
*/
@Slf4j
@SuppressWarnings("all")
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class CacheUtil {
private static final CacheManager CACHE_MANAGER = SpringUtil.getBean(CacheManager.class);
/**
* 缓存数据
* 如果cacheName不存在,则抛异常
* 如果key不存在,则创建新缓存
* 如果key存在 在更新缓存
*
* @param cacheName 缓存名称
* @param key 键
* @param value 值
*/
public static <T> void putCache(String cacheName, String key, T value) {
getCache(cacheName).put(key, value);
}
/**
* 提取缓存的值
*
* @param cacheName 缓存名称
* @param key 键
*/
public static <T> T getCacheValue(String cacheName, String key) {
CaffeineCache caffeineCache = getCache(cacheName);
if (null == caffeineCache.get(key)) {
return null;
}
return (T) caffeineCache.get(key).get();
}
/**
* 移除某个缓存
*
* @param cacheName 缓存名称
* @param key 键
*/
public static void delCache(String cacheName, Object key) {
getCache(cacheName).evict(key);
}
/**
* 清空缓存
*
* @param cacheName 缓存名称
*/
public static void clearCaches(String cacheName) {
getCache(cacheName).clear();
}
/**
* 查询缓存清单
*/
public static Collection<String> listCacheNames() {
return CACHE_MANAGER.getCacheNames();
}
/**
* 查询缓存性能参数
*/
public static Map<String, CacheStats> listCachesStats() {
Map<String, CacheStats> cacheStatses = new HashMap<>();
Collection<String> cacheNames = listCacheNames();
cacheNames.forEach(cacheName -> {
com.github.benmanes.caffeine.cache.Cache<Object, Object> cache = getCache(cacheName).getNativeCache();
CacheStats cacheStats = cache.stats();
cacheStatses.put(cacheName, cacheStats);
});
return cacheStatses;
}
/**
* 获取 CaffeineCache
*
* @param cacheName 缓存名称
* @return CaffeineCache
*/
public static CaffeineCache getCache(String cacheName) {
Cache cache = CACHE_MANAGER.getCache(cacheName);
if (null == cache) {
return null;
}
return (CaffeineCache) cache;
}
}
3. 使用缓存注解
在你想要缓存其结果的方法上使用@Cacheable
注解。这个注解会告诉Spring在调用方法前检查缓存中是否已有结果,如果有的话,直接从缓存中获取,否则执行方法并将结果存储在缓存中。
Java
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class MyService {
@Cacheable(value = "myCache")
public String getData(String key) {
// 耗时的操作,如查询数据库
return "data for " + key;
}
}
或者使用工具类
CacheUtil.putCache(CacheConstant.KEY_CACHE, CacheConstant.AUTH_KEY, accessToken);
public interface CacheConstant {
/**
* 密钥缓存
*/
String KEY_CACHE = "keyCache";
/**
* 登录密钥
*/
String AUTH_KEY = "auth:key";
}
4. 配置缓存管理器
你可以配置不同的缓存管理器,例如使用Caffeine。在application.properties
或application.yml
中添加配置:
Properties
# 缓存配置
cache:
caffeine:
enabled: true
# 全局配置
cacheName: globalCache
spec: maximumSize=10000,expireAfterWrite=1d
# 自定义配置,cacheName相同可覆盖全局配置
configs:
- cacheName: keyCache
spec: maximumSize=200,expireAfterWrite=30m
如果你想要更详细的配置,可以在@Configuration
类中创建一个CaffeineCacheManager
bean,并对其进行自定义配置。
Java
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.github.benmanes.caffeine.cache.Caffeine;
@Configuration
@EnableCaching
public class CaffeineCacheConfig {
@Bean
public CaffeineCacheManager caffeineCacheManager() {
CaffeineCacheManager cacheManager = new CaffeineCacheManager();
cacheManager.setCaffeine(Caffeine.newBuilder()
.maximumSize(500)
.expireAfterWrite(5, TimeUnit.MINUTES));
return cacheManager;
}
}
以上步骤将帮助你在Spring Boot应用中设置并使用本地缓存。确保根据你的具体需求调整缓存策略和配置。