Spirng Cache(第三篇)Redis缓存配置
从3.1版开始,Spring Framework提供了对现有Spring应用程序透明地添加缓存的支持。与事务 支持类似,缓存抽象允许一致地使用各种缓存解决方案,而对代码的影响最小。
从Spring 4.1开始,通过JSR-107注释和更多自定义选项的支持,缓存抽象得到了显着改进。
这篇介绍下如果根据Spring 缓存的Redis
实现。
在Spring boot 1.5+
和Spring boot 2.0+
版本,分别使用配置文件和注解实现。
文章目录
切换到Redis缓存
把前面内存缓存切换到Redis
缓存,只需要修改配置,业务代码不动。
修改配置文件 application.yml
,添加Redis
相关配置。redis 安装
添加Redis
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
将上一章自定义配置都删除掉,不然会影响到Redis
配置
application.yml
配置
spring:
redis:
host: localhost
port: 6379
这样就可以切换到Redis缓存了,别忘记重写Book
实体的equals
和hashCode
单元测试
@Test
public void findBook() {
Book book1 = bookService.findBook(ISBN);
Book book2 = bookService.findBook(ISBN);
Book book3 = bookService.findBook(ISBN);
assert book1.equals(book2);
assert book1.equals(book3);
}
Redis缓存自定义配置 application.yml
此配置适用于Spring-boot1.5.x
版本。
添加以下几项自定义配置
default-expiration
默认过期时间 单位秒cache-null-values
缓存null值key-prefix
全局缓存前缀 默认值spring-cache
expires
指定缓存名称过期时间 单位秒
properties配置类,省略Get/Set方法
@ConfigurationProperties("spring.cache.redis")
public class RedisCacheProperties {
/**
* 全局默认过期时间 单位秒
*/
private Long defaultExpiration;
/**
* 是否缓存null值
*/
private boolean cacheNullValues = true;
/**
* 缓存前缀
*/
private String keyPrefix = "spring-cache";
/**
* 指定缓存名称过期时间 单位秒
*/
private Map<String, Long> expires;
}
覆盖Redis默认配置
@EnableCaching
@EnableConfigurationProperties({
RedisCacheProperties.class, CacheProperties.class})
public class RedisCacheConfig implements RedisCachePrefix {
private final RedisSerializer<String> serializer = new StringRedisSerializer();
private final RedisCacheProperties redisCacheProperties;
private final CacheProperties cacheProperties;
public RedisCacheConfig(RedisCacheProperties redisCacheProperties, CacheProperties cacheProperties) {
this.redisCacheProperties = redisCacheProperties;
this.cacheProperties = cacheProperties;
}
/**
* 覆盖redis 默认缓存管理器
*/
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> redisTemplate = redisTemplate(redisConnectionFactory);
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate, null, redisCacheProperties.isCacheNullValues());
if (redisCacheProperties.getKeyPrefix() != null) {
cacheManager.setUsePrefix(true);
}
cacheManager.setCachePrefix(this);
List<String> cacheNames = this.cacheProperties.getCacheNames();
if (!cacheNames.isEmpty()) {
cacheManager.setCacheNames(cacheNames);
}
if (redisCacheProperties.getDefaultExpiration() != null)