Spring Cache 入门
核心概念
- Spring Cache 是基于 AOP 的声明式缓存抽象层,通过 CacheManager 接口解耦应用与具体缓存实现,支持 Caffeine、Redis、Ehcache 等多种缓存产品。
核心接口
- CacheManager:缓存管理器接口,定义缓存操作规范
- Cache:缓存操作抽象,提供 get、put、evict 等操作
核心模块
Spring Cache 的核心功能位于 spring-context 模块中,提供了基础的缓存抽象和注解支持。
扩展支持
spring-context-support 模块提供了对第三方缓存产品的集成支持,包括:
- Ehcache
- Caffeine
- Redis
- Guava Cache
<!-- Maven 依赖示例 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
启用缓存
Spring Boot 自动配置
添加 @EnableCaching 注解即可,默认使用 ConcurrentMapCacheManager。可通过 application.properties 定制:
spring.cache.type=caffeine
Spring Boot 注解配置
在Spring Boot的启动类上加上@EnableCaching 注解即可
@SpringBootApplication
@EnableCaching
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
Java 注解配置
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public CacheManager cacheManager() {
return new ConcurrentMapCacheManager("users", "orders");
}
}
XML 配置
<cache:annotation-driven />
<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
<property name="caches">
<set>
<bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" name="users"/>
<bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" name="orders"/>
</set>
</property>
</bean>
缓存注解
@Cacheable
作用:在方法执行前检查缓存,如果存在则直接返回,否则执行方法并缓存结果。
核心参数:
value
:缓存名称,必填key
:缓存键,支持 SpEL 表达式condition
:条件表达式,满足条件才缓存unless
:否定条件,满足条件则不缓存sync
:是否同步执行,防止缓存击穿
@CachePut
作用:无论缓存是否存在,始终执行方法并更新缓存。
核心参数:
value
:缓存名称,必填key
:缓存键,支持 SpEL 表达式condition
:条件表达式,满足条件才更新缓存
@CacheEvict
作用:删除缓存条目。
核心参数:
value
:缓存名称,必填key
:缓存键,支持 SpEL 表达式allEntries
:是否删除所有条目beforeInvocation
:是否在方法执行前删除
@Caching
作用:组合多个缓存注解。
核心参数:
cacheable
:@Cacheable 数组put
:@CachePut 数组evict
:@CacheEvict 数组
@CacheConfig
作用:类级缓存配置,统一设置公共属性。
核心参数:
cacheNames
:缓存名称列表keyGenerator
:键生成器cacheManager
:缓存管理器
缓存实现切换
Caffeine 配置
@Bean
public CacheManager cacheManager() {
CaffeineCacheManager manager = new CaffeineCacheManager();
manager.setCaffeine(Caffeine.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES)
.maximumSize(1000));
return manager;
}
Redis 配置
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10))
.serializeValuesWith(RedisSerializationContext.SerializationPair
.fromSerializer(new GenericJackson2JsonRedisSerializer()));
return RedisCacheManager.builder(factory)
.cacheDefaults(config)
.build();
}
剩下的等我学了更多再更新