如何配置
1. maven
<!-- 使用spring cache --><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId></dependency><!-- redis --><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId></dependency><!-- 为了解决 ClassNotFoundException: org.apache.commons.pool2.impl.GenericObjectPoolConfig --><dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.0</version></dependency>
复制代码
2.application 配置
# Redis数据库索引(默认为0)spring.redis.database=0 # Redis服务器地址spring.redis.host=localhost# Redis服务器连接端口spring.redis.port=6379 # Redis服务器连接密码(默认为空)#spring.redis.password=yourpwd# 连接池最大连接数(使用负值表示没有限制)spring.redis.lettuce.pool.max-active=8 # 连接池最大阻塞等待时间 spring.redis.lettuce.pool.max-wait=-1ms# 连接池中的最大空闲连接spring.redis.lettuce.pool.max-idle=8 # 连接池中的最小空闲连接spring.redis.lettuce.pool.min-idle=0 # 连接超时时间(毫秒)spring.redis.timeout=5000ms#配置缓存相关cache.default.expire-time=200cache.user.expire-time=180cache.user.name=test
复制代码
3. @EnableCaching
标记注解 @EnableCaching,开启缓存,并配置 Redis 缓存管理器,需要初始化一个缓存空间。在缓存的时候,也需要标记使用哪一个缓存空间
@Configuration@EnableCachingpublic class RedisConfig {
@Value("${cache.default.expire-time}") private int defaultExpireTime; @Value("${cache.user.expire-time}") private int userCacheExpireTime; @Value("${cache.user.name}") private String userCacheName;
/** * 缓存管理器 * * @param lettuceConnectionFactory * @return */ @Bean public CacheManager cacheManager(RedisConnectionFactory lettuceConnectionFactory) { RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig(); // 设置缓存管理器管理的缓存的默认过期时间 defaultCacheConfig = defaultCacheConfig.entryTtl(Duration.ofSeconds(defaultExpireTime)) // 设置 key为string序列化 .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())) // 设置value为json序列化 .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())) // 不缓存空值 .disableCachingNullValues(); Set<String> cacheNames = new HashSet<>(); cacheNames.add(userCacheName); // 对每个缓存空间应用不同的配置 Map<String, RedisCacheConfiguration> configMap = new HashMap<>(); configMap.put(userCacheName, defaultCacheConfig.entryTtl(Duration.ofSeconds(userCacheExpireTime))); RedisCacheManager cacheManager = RedisCacheManager.builder(lettuceConnectionFactory) .cacheDefaults(defaultCacheConfig) .initialCacheNames(cacheNames) .withInitialCacheConfigurations(configMap) .build(); return cacheManager; }}
复制代码
到此配置工作已经结束了
Spring Cache 使用
@Service@CacheConfig(cacheNames="user")// cacheName 是一定要指定的属性,可以通过 @CacheConfig 声明该类的通用配置public class UserService {
/** * 将结果缓存,当参数相同时,不会执行方法,从缓存中取 * * @param id * @return */ @Cacheable(key = "#id") public User findUserById(Integer id) { System.out.println("===> findUserById(id), id = " + id); return new User(id, "taven"); }
/** * 将结果缓存,并且该方法不管缓存是否存在,每次都会执行 * * @param user * @return */ @CachePut(key = "#user.id") public User update(User user) { System.out.println("===> update(user), user = " + user); return user; }
/** * 移除缓存,根据指定key * * @param user */ @CacheEvict(key = "#user.id") public void deleteById(User user) { System.out.println("===> deleteById(), user = " + user); }
/** * 移除当前 cacheName下所有缓存 * */ @CacheEvict(allEntries = true) public void deleteAll() { System.out.println("===> deleteAll()"); }
}
复制代码
注解作用
@Cacheable 将方法的结果缓存起来,下一次方法执行参数相同时,将不执行方法,返回缓存中的结果。
@CacheEvict 移除指定缓存 @CachePut 标记该注解的方法总会执行,根据注解的配置将结果缓存。@Caching 可以指定相同类型的多个缓存注解,例如根据不同的条件 @CacheConfig 类级别注解,可以设置一些共通的配置
@CacheConfig(cacheNames="user"), 代表该类下的方法均使用这个 cacheNames
Spring Cache 注解
1. @EnableCaching 做了什么
@EnableCaching 注释触发后置处理器, 检查每一个 Spring bean 的 public 方法是否存在缓存注解。如果找到这样的一个注释, 自动创建一个代理拦截方法调用和处理相应的缓存行为。
2. 常用缓存注解简述
2.1 @Cacheable
将方法的结果缓存,必须要指定一个 cacheName(缓存空间)
@Cacheable("books")public Book findBook(ISBN isbn) {...}
复制代码
默认 cache key
缓存的本质还是以 key-value 的形式存储的,默认情况下我们不指定 key 的时候 ,使用 SimpleKeyGenerator 作为 key 的生成策略
注意:当使用默认策略时,我们的参数需要有 有效的 hashCode()和 equals()方法
自定义 cache key
@Cacheable(cacheNames="books", key="#isbn")public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)@Cacheable(cacheNames="books", key="#isbn.rawNumber")public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)@Cacheable(cacheNames="books", key="T(someType).hash(#isbn)")public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)
复制代码
如上,配合 Spring EL 使用,下文会详细介绍 Spring EL 对 Cache 的支持
自定义 keyGenerator
@Cacheable(cacheNames="books", keyGenerator="myKeyGenerator")public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)
复制代码
实现 KeyGenerator 接口可以自定义 cache key 的生成策略
自定义 cacheManager
@Cacheable(cacheNames="books", cacheManager="anotherCacheManager") public Book findBook(ISBN isbn) {...}
复制代码
当我们的项目包含多个缓存管理器时,可以指定具体的缓存管理器,作为缓存解析
同步缓存
在多线程环境中,可能会出现相同的参数的请求并发调用方法的操作,默认情况下,spring cache 不会锁定任何东西,相同的值可能会被计算几次,这就违背了缓存的目的
对于这些特殊情况,可以使用sync属性。此时只有一个线程在处于计算,而其他线程则被阻塞,直到在缓存中更新条目为止。
@Cacheable(cacheNames="foos", sync=true) public Foo executeExpensiveOperation(String id) {...}
复制代码
条件缓存
@Cacheable(cacheNames="book", condition="#name.length() < 32") public Book findBook(String name)
复制代码
@Cacheable(cacheNames="book", condition="#name.length() < 32", unless="#result?.hardback")public Optional<Book> findBook(String name)
复制代码
Spring EL 对 Cache 的支持
NameLocationDescriptionExamplemethodNameRoot object 被调用的方法的名称
#root.methodName methodRoot object 被调用的方法 #root.method.name targetRoot object 当前调用方法的对象 #root.targettargetClassRoot object 当前调用方法的类 #root.targetClassargsRoot object 当前方法的参数 #root.args[0]cachesRoot object 当前方法的缓存集合 #root.caches[0].nameArgument nameEvaluation context 当前方法的参数名称 #iban or #a0 (you can also use #p0 or #p<#arg> notation as an alias).resultEvaluation context 方法返回的结果(要缓存的值)。只有在 unless 、@CachePut(用于计算键)或 @CacheEvict(beforeInvocation=false)中才可用.对于支持的包装器(例如 Optional),#result 引用的是实际对象,而不是包装器 #result
2.2 @CachePut
这个注解和 @Cacheable 有点类似,都会将结果缓存,但是标记 @CachePut 的方法每次都会执行,目的在于更新缓存,所以两个注解的使用场景完全不同。@Cacheable 支持的所有配置选项,同样适用于 @CachePut
@CachePut(cacheNames="book", key="#isbn")public Book updateBook(ISBN isbn, BookDescriptor descriptor)
复制代码
需要注意的是,不要在一个方法上同时使用 @Cacheable 和 @CachePut
2.3 @CacheEvict
用于移除缓存
@CacheEvict(cacheNames="book", key="#isbn")public Book updateBook(ISBN isbn, BookDescriptor descriptor)
复制代码
@CacheEvict(cacheNames="books", allEntries=true) public void loadBooks(InputStream batch
复制代码
2.4 @Caching
可以让你在一个方法上嵌套多个相同的 Cache 注解(@Cacheable, @CachePut, @CacheEvict),分别指定不同的条件
@Caching(evict = { @CacheEvict("primary"), @CacheEvict(cacheNames="secondary", key="#p0") })public Book importBooks(String deposit, Date date)
复制代码
2.5 @CacheConfig
类级别注解,用于配置一些共同的选项(当方法注解声明的时候会被覆盖),例如 CacheName。
支持的选项如下:
@Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface CacheConfig {
String[] cacheNames() default {};
String keyGenerator() default "";
String cacheManager() default "";
String cacheResolver() default "";}
复制代码
评论