在搭建完集群环境后,需要考虑的问题就是用户访问的session如何共享?
我们可以利用redis集群做主从复制,利用redis数据库的最终一致性,将session信息存入redis中。当服务器发现session不在本机的内存中就会去redis中查找,由于redis数据库是独立于应用服务器的数据库,所以可以做到session的共享。
SpringBoot提供SpringSession来完成session共享。
那么如何实现session共享
Step1.在pom.xml加入下面的依赖
<!--注意这个依赖没有版本号-->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
<version>1.4.7.RELEASE</version>
</dependency>
Step2:在application.yml中添加redis的配置
redis:
host: localhost
password:
port: 6379
host:代表的是redis的地址。
password:代表的是redis服务的密码。
port:代表的是redis服务占用的端口号。
Step3:在springBoot的启动类中添加“@EnableRedisHttpSession”的注解。
Step4:测试
@RestController
public class UserController {
@RequestMapping(value="main",method = RequestMethod.GET)
public String main(HttpServletRequest request){
HttpSession session = request.getSession();
String sessionId = (String) session.getAttribute("sessionId");
if(sessionId != null){
System.out.println("main sessionId:"+sessionId);
return "session已存在";
}else{
return "session不存在";
}
}
@RequestMapping(value="/doLogin", method=RequestMethod.GET)
public String doLogin(HttpServletRequest request) {
System.out.println("I do real login here");
HttpSession session = request.getSession();
String sessionId = UUID.randomUUID().toString();
session.setAttribute("sessionId", sessionId);
System.out.println("login sessionId:" + sessionId);
return "session已存入";
}
}