spring boot整合使用redis实现session共享
引入依赖
新建gradle的spring boot应用
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
compile group: 'org.springframework.session', name: 'spring-session-data-redis', version: '2.1.1.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.1.1.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-redis', version: '2.1.1.RELEASE'
compileOnly 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
修改application.yml
配置文件:
spring:
application:
name: redis-session
redis:
host: 127.0.0.1
port: 6379
session:
store-type: redis
server:
port: 8080
# port: 8081
获取session
@RestController
public class SpringRedisSessionController {
@Value("${server.port}")
private int port;
@RequestMapping(value = "/getSession", method = RequestMethod.GET)
public Map<String, Object> getSession(HttpServletRequest request){
Map<String, Object> map = new HashMap<>();
map.put("port", port);
map.put("session_id", request.getSession().getId());
return map;
}
}
分别启动端口为8080
和8081
的两个boot实例,在浏览器分别访问: http://localhost:8080/getSession
和http://localhost:8081/getSession
,
可以看到当访问http://localhost:8080/getSession
时返回:
{
"port": 8080,
"session_id": "929bf507-e380-4e9d-bd1f-6e6fe5075aa2"
}
而当访问http://localhost:8081/getSession
时返回:
{
"port": 8081,
"session_id": "929bf507-e380-4e9d-bd1f-6e6fe5075aa2"
}
可以发现不同实例返回的session_id是相同的,即实现了session共享的效果
后序
在访问/getSession
请求的时候,可以发现在redis服务器中已经写入数据:
localhost:6379> keys *
1) "spring:session:sessions:expires:929bf507-e380-4e9d-bd1f-6e6fe5075aa2"
2) "spring:session:sessions:929bf507-e380-4e9d-bd1f-6e6fe5075aa2"
3) "spring:session:expirations:1547091540000"