Redis实现分布式Session管理的机制详解

来自:互联网
时间:2021-01-19
阅读:

一. Redis实现分布式Session管理

1. Memcached管理机制

Redis实现分布式Session管理的机制详解

2. Redis管理机制

1.redis的session管理是利用spring提供的session管理解决方案,将一个应用session交给Redis存储,整个应用中所有session的请求都会去redis中获取对应的session数据。

Redis实现分布式Session管理的机制详解

二. SpringBoot项目开发Session管理

1. 引入依赖pop.xml

 <!--springboot-redis-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>

    <!--spring-data-redis session 管理-->
    <dependency>
      <groupId>org.springframework.session</groupId>
      <artifactId>spring-session-data-redis</artifactId>
    </dependency>

    <!--排除内嵌tomcat-->
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
    </dependency>

2. 开发Session管理配置类(使用注解)

Redis实现分布式Session管理的机制详解

@Configuration
@EnableRedisHttpSession //将整个应用中使用session的数据全部交给redis处理
public class RedisSessionManager {

}

3. Controller层设计

package com.xizi.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("test")
public class TestController {

  //使用redis 的session管理 注意:当session中数据发生变化时必须将session中变化的数据同步到redis中
  @RequestMapping("test")
  public void test(HttpServletRequest request, HttpServletResponse response) throws IOException {
    List<String> list = (List<String>) request.getSession().getAttribute("list");
    if(list==null){
      list = new ArrayList<>();
    }
    list.add("xxxx");
    request.getSession().setAttribute("list",list);//每次session变化都要同步session

    response.getWriter().println("size: "+list.size());
    response.getWriter().println("sessionid: "+request.getSession().getId());
  }

  @RequestMapping("logout")
  public void logout(HttpServletRequest request){
    //退出登录
    request.getSession().invalidate();//失效
  }
}

4.打包测试

Redis实现分布式Session管理的机制详解

三 . Nginx+Tomcat集群+Redis测试

1.Nginx相关配置

Redis实现分布式Session管理的机制详解
Redis实现分布式Session管理的机制详解
Redis实现分布式Session管理的机制详解

2.Tomcat集群

Redis实现分布式Session管理的机制详解

//这是tom4 后面的两个端口号依次+1
//关闭端口
<Server port="8003" shutdown="SHUTDOWN">

//连接端口
<Connector port="8989" protocol="HTTP/1.1"
        connectionTimeout="20000"
        redirectPort="8443" />

<Connector port="10010" protocol="AJP/1.3" redirectPort="8443" />

Redis实现分布式Session管理的机制详解

改变初始页面index.jsp

Redis实现分布式Session管理的机制详解

3.Redis集群

已经开启了,不会的去看我前面的Redis集群搭建博客

Redis实现分布式Session管理的机制详解
Redis实现分布式Session管理的机制详解

4. 测试

上传war包到三个Tomcat的Webapps目录下

Redis实现分布式Session管理的机制详解

直接访问Nginx页面,反向代理了Tomcat集群

Redis实现分布式Session管理的机制详解
Redis实现分布式Session管理的机制详解
Redis实现分布式Session管理的机制详解

GiF演示一波

Redis实现分布式Session管理的机制详解

返回顶部
顶部