[SpringBoot]集成redis来实现session共享

增加依赖

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

启用配置

1
2
3
@Configuration
@EnableRedisHttpSession
public class RedisSessionConfig {}

增加redis配置

application.properties

1
2
3
4
spring.redis.host=localhost  
spring.redis.port=6379
spring.redis.password=
spring.redis.timeout=5000

或者
application.yml
1
2
3
4
5
6
spring:
redis:
host: localhost
port: 6379
password:
timeout: 5000

创建controller测试

1
2
3
4
5
6
7
8
@RestController  
@RequestMapping(value = "/hello")
public class QuickRun {
@RequestMapping(value = "/world", method = RequestMethod.GET)
public void helloworld(HttpServletRequest req){
req.getSession().setAttribute("hello", "world");
}
}

启动应用进行访问测试http://localhost/hello/world

检查redis数据

1
redis-cli keys '*'

可以看见以spring前缀开始的数据,表示成功接入session的redis共享

清理数据

1
redis-cli keys '*' | xargs redis-cli del

结束

参考官方文章-Spring Session Redis