Spring-Session+Redis实现session共享

1、添加依赖

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-redis</artifactId>
    <version>2.0.9.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.session</groupId>
    <artifactId>spring-session-data-redis</artifactId>
    <version>2.0.5.RELEASE</version>
</dependency>
<!-- spring-session-data-redis 依赖包 -->
<dependency>
    <groupId>io.lettuce</groupId>
    <artifactId>lettuce-core</artifactId>
    <version>5.1.0.RC1</version>
</dependency>

2、配置

spring-mvc.xml:

<!-- RedisHttpSessionConfiguration -->
<bean
        class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration">
    <property name="maxInactiveIntervalInSeconds" value="${redis.session.timeout}" />    <!-- session过期时间,单位是秒 -->
</bean>

<!--LettuceConnectionFactory -->
<bean
        class="org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory"
        p:host-name="127.0.0.1" p:port="6379" p:password="meander" />

web.xml添加拦截器

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:applicationContext*.xml</param-value>
</context-param>

<!-- 这个filter 要放在第一个 -->
<filter>
    <filter-name>springSessionRepositoryFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
    <filter-name>springSessionRepositoryFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>ERROR</dispatcher>
</filter-mapping>

3、使用spring-session

只要使用标准的servlet api调用session,在底层就会通过Spring Session得到的,并且会存储到Redis或其他你所选择的数据源中。

这里我们写个测试类LoginController:

@RequestMapping("/login")
public ModelAndView login(HttpServletRequest request, HttpServletResponse response) {
    Map<String, Object> model = new HashMap<String, Object>();
    String userName = request.getParameter("userName");
    String password = request.getParameter("password");
    HttpSession session = request.getSession(true);
    String p = request.getParameter("p");
    if(StringUtils.isNotEmpty(p) || StringUtils.isEmpty((String)session.getAttribute("p"))) {
      session.setAttribute("p", p);
    }
    return new ModelAndView("login", model);
}

然后写一个login.jsp页面:

<html>
<body>
<div><% String url = request.getLocalAddr() + ":" + request.getLocalPort(); %></div>
<div><%= url %></div>
<div>传入参数:${p}</div>
</body>
</html>

启动两个tomcat,一个通过http://127.0.0.1:8080/login?p=yori访问,

另一个通过http://127.0.0.1:8085/login

​​​​​​​

猜你喜欢

转载自blog.csdn.net/kongtong2004/article/details/83046354