Spring Boot 中 Redis 的使用

Posted by 彭超 on 2019-08-18
Estimated Reading Time 4 Minutes
Words 883 In Total
Viewed Times

整合 Redis

引入依赖

pox.xml 中引入 org.apache.commons:commons-pool2org.springframework.boot:spring-boot-starter-data-redis 依赖

1
2
3
4
5
6
7
8
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

单机模式的相关配置

application.yml 中添加 redis 配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
spring:
redis:
database: 0
# Redis服务器地址
host: localhost
# Redis服务器连接端口
port: 6379
# Redis服务器连接密码(默认为空)
password:
#连接池最大连接数(使用负值表示没有限制)
pool.max-active: 8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
pool.max-wait: -1
# 连接池中的最大空闲连接
pool.max-idle: 8
# 连接池中的最小空闲连接
pool.min-idle: 0
# 连接超时时间(毫秒)
timeout: 0

哨兵集群模式的相关配置

application.yml 中添加 redis 及哨兵集群的配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
spring:
redis:
lettuce:
pool:
# 最大连接数
max-active: 8
# 最大空闲连接数
max-idle: 8
# 最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1ms
# 最小空闲连接数
min-idle: 0
sentinel:
# 哨兵集群主节点名
master: mymaster
# 哨兵集群各节点
nodes: {ip}:{port}, {ip}:{port}, {ip}:{port}

实现增删改查

注意:写入缓存的数据(如实体类)需要实现序列化,否则向 Redis 中存取数据会抛出异常

创建 RedisService

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public interface RedisService {

/**
* 存储缓存
* @param key
* @param value
* @param seconds
*/
void set(String key, Object value, long seconds);

/**
* 获取缓存
* @param key
* @return
*/
Object get(String key);

/**
* 删除缓存
* @param key
*/
boolean del(String key);
}

创建 RedisServiceImpl

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Service
public class RedisServiceImpl implements RedisService {

@Autowired
private RedisTemplate redisTemplate;

@Override
public void set(String key, Object value, long seconds) {
redisTemplate.opsForValue().set(key, value, seconds, TimeUnit.SECONDS);
}

@Override
public Object get(String key) {
return redisTemplate.opsForValue().get(key);
}

@Override
public boolean del(String key) {
return redisTemplate.delete(key);
}
}

解决序列化乱码

spring-data-redisRedisTemplate<K, V> 模板类在操作 redis 时默认使用 JdkSerializationRedisSerializer 来进行序列化,如下:

1
2
3
4
5
6
private boolean enableDefaultSerializer = true;
private RedisSerializer<?> defaultSerializer = new JdkSerializationRedisSerializer();
private RedisSerializer keySerializer = null;
private RedisSerializer valueSerializer = null;
private RedisSerializer hashKeySerializer = null;
private RedisSerializer hashValueSerializer = null;

创建 RedisListenerConfig 配置类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Configuration
public class RedisListenerConfig {

@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {

RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
return container;
}

@Bean(name="redisTemplate")
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, String> template = new RedisTemplate<>();
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
template.setConnectionFactory(factory);
template.setKeySerializer(redisSerializer);
template.setValueSerializer(redisSerializer);
template.setHashValueSerializer(redisSerializer);
template.setHashKeySerializer(redisSerializer);
return template;
}
}

实现共享 Session

引入依赖

pom.xml 中添加 spring-session-data-redis 依赖

1
2
3
4
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>

相关配置

创建 RedisConfiguration 配置类

1
2
3
4
5
6
7
8
import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;

@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 60 * 60 * 24)
public class RedisConfiguration {

}

Controller

创建存取 session 的接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class IndexController {

@GetMapping(value = "put")
public String putSession(HttpSession session) {
session.setAttribute("userId", "2384783434");
return "ok";
}

@GetMapping(value = "get")
public String getSession(HttpSession session) {
return (String) session.getAttribute("userId");
}

}

测试共享 Session

分别启动两次项目,第一次启动项目设置端口为 80,第二次启动项目设置端口为 81

默认情况下,Intellij IDEA 不允许同时启动两个相同的项目,需要在 Run/Debug Configurations 页面中设置允许同时运行多个相同的项目,勾选 Allow parallel run 选项即可

《Spring Boot 中 Redis 的使用》

最后在浏览器中先后访问 http://localhost/puthttp://localhost:81/get


If you like this blog or find it useful for you, you are welcome to comment on it. You are also welcome to share this blog, so that more people can participate in it. If the images used in the blog infringe your copyright, please contact the author to delete them. Thank you !