springboot +springsession+redis 做session共享
阿新 • • 發佈:2018-12-11
springboot版本 2.0.5.RELEASE
maven:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> </dependency>
啟動類:
@SpringBootApplication
@ComponentScan(value = "com.qjs.*")
@EnableRedisHttpSession
public class CollectionApplication {
public static void main(String[] args) {
SpringApplication.run(CollectionApplication.class, args);
}
}
controller:
@RestController public class SessionShare { //模擬登陸 @ResponseBody @RequestMapping(value = "/Login",method = RequestMethod.GET) public String Login(HttpServletRequest request) { request.getSession().setAttribute("username","ethan"); return request.getSession().getId(); } @ResponseBody @RequestMapping(value = "/getSession",method = RequestMethod.GET) public String getSession(HttpServletRequest request) { return request.getSession().getAttribute("username")+"@@"+ request.getSession().getId(); } }
此時最簡版專案搭建完畢,拷貝專案,分別啟動這兩個專案,埠分別為8080,9090
先模擬登陸
http://localhost:8080/Login
返回sessionId:eb30fc4b-fff3-408e-bbf9-20ae9e9a9c7c
再訪問:http://localhost:8080/getSession
返回:[email protected]@eb30fc4b-fff3-408e-bbf9-20ae9e9a9c7c
訪問9090埠的專案
http://localhost:9090/getSession 返回:[email protected]@eb30fc4b-fff3-408e-bbf9-20ae9e9a9c7c
檢視redis
不要用keys*(阻塞),用scan命令(非阻塞)
xxxx:8001> scan 0 match *session* count 10
1) "0"
2) 1) "spring:session:sessions:expires:eb30fc4b-fff3-408e-bbf9-20ae9e9a9c7c"
xxxx:8001>
完成的session共享