1. 程式人生 > >Spring-Session+Redis實現session共享

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

​​​​​​​