Spring Session 进行session共享

在搭建完集群环境后,需要考虑的问题就是用户访问的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已存入";
    }
}

注意:在集群的环境下要想做到每个服务都可以共享session那么就需要在每个服务中都添加依赖、注解和redis的配置
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值