Spring Boot下配置Redis缓存

记录配置过程

题图:made by Keynote

一、添加Redis支持

在build.gradle文件的dependencies模块下添加

1
compile("org.springframework.boot:spring-boot-starter-redis")

二、配置Redis

想要使得redis可用,我们首先需要为缓存配置一个CacheManager、创建连接用的ConnectionFactory以及与Redis交互用的template(Spring的特点^_^)。当然,如果需要自定义主键,还要配置一个KeyGenerator,否则默认使用参数名作为主键。

下面示例代码中RedisProperties类用来读取配置信息,RedisConfiguration用来对redis进行配置。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
@Configuration
@EnableCaching
public class RedisConfiguration extends CachingConfigurerSupport {
@Autowired
private RedisProperties redisProperties;
@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
if (params.length == 0) {
return Constants.CACHE_KEY_PREFIX + method.getName();
}
if (params.length == 1) {
Object param = params[0];
if (param != null && !param.getClass().isArray()) {
return Constants.CACHE_KEY_PREFIX + method.getName() + "_" + param;
}
}
return Constants.CACHE_KEY_PREFIX + method.getName() + " [" + StringUtils.arrayToCommaDelimitedString(params) + "]";
}
};
}
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
redisCacheManager.setDefaultExpiration(redisProperties.getExpire());
return redisCacheManager;
}
@Bean(name = "redisTemplate")
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(factory);
redisTemplate.setValueSerializer(new RedisSerializer<Object>() {
@Override
public byte[] serialize(Object object) throws SerializationException {
if (object == null) {
return new byte[0];
}
if (!(object instanceof Serializable)) {
throw new IllegalArgumentException("RedisSerializer.serialize requires a Serializable payload "
+ "but received an object of type [" + object.getClass().getName() + "]");
}
return SerializationUtils.serialize((Serializable) object);
}
@Override
public Object deserialize(byte[] bytes) throws SerializationException {
if (bytes == null || bytes.length == 0) {
return null;
}
return SerializationUtils.deserialize(bytes);
}
});
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
@Bean
public JedisConnectionFactory redisConnectionFactory() {
JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory();
// Defaults
redisConnectionFactory.setHostName(redisProperties.getHost());
redisConnectionFactory.setPort(redisProperties.getPort());
redisConnectionFactory.setDatabase(redisProperties.getIndex());
redisConnectionFactory.setPassword(redisProperties.getPassword());
return redisConnectionFactory;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
@Component
@ConfigurationProperties(prefix = "redis")
public class RedisProperties {
private String host;
private int port;
private String password;
private int expire;
private int index;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getExpire() {
return expire;
}
public void setExpire(int expire) {
this.expire = expire;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}

三、Redis服务器配置

在application.yml文件中进行配置

1
2
3
4
5
6
redis:
host: 127.0.0.1
port: 6379
password: xxxxxxx
expire: 120
index: 11

四、应用

1.@Cacheable

通过以上配置,spring会自动检测到redis的缓存配置。
在需要缓存结果的方法上添加@Cacheable注解,即可实现自动使用redis进行缓存。

2.redisTemplate

某些情况下,@Cacheable注解有可能不适用,也可以直接获取redisTemplate来直接操作redis缓存。
与JDBCTemplate等Template相同,RedisTemplate也对redis的相关操作进行很好的封装,使用起来十分方便。
因为redisTemplate已经注册为Spring管理的Bean,所以可以通过getBean()方法直接获取。

五、参考文章

Caching Data in Spring Using Redis