架構設計之Spring-Session分布式集群會話管理


前言

通常在web開發中,會話管理是很重要的一部分,用於存儲與用戶相關的一些數據。對於JAVA開發者來說,項目中的session一般由Tomcat或者jetty容器來管理。

特點介紹

盡管使用特定的容器可以很好地實現會話管理,但是獨立容器掛掉或者由於其他原因重啟會導致用戶信息丟失,並且無法支持分布式集群會話管理。

上圖舉例:

12.png

這是一個簡單的負載均衡集群架構模型,后端三台Tomcat服務,假設每台服務都使用自己的會話管理,而集群策略是基於加權輪詢的方式實現。試想一下,用戶是不是永遠無法登陸系統?

當然,你可能會想,我可以使用基於IP_hash的方式實現負載均衡嘛。但是如果地區分布相對單一,產生的hash值分布可能也不會太均勻,那就起不到負載均衡的作用了。

一般來說,有兩種解決方案,session復制和session統一管理。對於session復制,簡單的幾台還是可以的,但是如果上百台甚至上千台就要考慮復制成本問題了。

對於統一session管理可以是關系型數據庫,比如MySql(基本不用,考慮到效率問題);非關系型數據庫 redis,memcache等等。

解決方案

  • 基於Tomcat的會話插件實現tomcat-redis-session-manager 和tomcat-memcache-session-manager,會話統一由NoSql管理。對於項目本身來說,無須改動代碼,只需要簡單的配置Tomcat的server.xml就可以解決問題。但是插件太依賴於容器,並且對於Tomcat各個版本的支持不是特別的好

  • 重寫Tomcat的session管理,代碼耦合度高,不利於維護。

  • 使用開源的session管理框架,比如spring_session,既不需要修改Tomcat配置,又無須重寫代碼,只需要配置相應的參數即可。

功能實現

下面,主要是基於spring_session實現的分布式集群會話管理案例。

項目需要使用到spring_Mvc4.2.5,spring_session-1.2.2和redis-3.2.8(需要自行安裝redis服務)。

配置相關JAR包(spring mvc相關jar包依賴自行配置):

<dependency>
  <groupId>org.springframework.session</groupId>
    <artifactId>spring-session-data-redis</artifactId>
    <version>1.2.2.RELEASE</version>
</dependency>

spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    
    <description>Spring MVC Configuration</description>
    
    <!-- 加載配置屬性文件 -->
	<context:property-placeholder ignore-unresolvable="true" location="classpath:config.properties" />
	<!-- 使用Annotation自動注冊Bean,只掃描@Controller -->
	<context:component-scan base-package="com.itstyle.web" use-default-filters="false"><!-- base-package 如果多個,用“,”分隔 -->
		<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
	</context:component-scan>
    <mvc:annotation-driven/>
	<!--啟動Spring MVC的注解功能,設置編碼方式,防止亂碼--> 
	<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">  
      <property name="messageConverters">     
         <list>     
             <bean class = "org.springframework.http.converter.StringHttpMessageConverter">     
                <property name = "supportedMediaTypes">  
                      <list>  
                          <value>text/html;charset=UTF-8</value>
                     </list>     
                </property>     
             </bean>     
         </list>     
      </property>   
    </bean>  
    <!-- REST中根據URL后綴自動判定Content-Type及相應的View -->
	<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
	    <property name="mediaTypes" >
	        <map> 
                <entry key="xml" value="application/xml"/> 
                <entry key="json" value="application/json"/> 
            </map>
	    </property>
        <property name="ignoreAcceptHeader" value="true"/>
        <property name="favorPathExtension" value="true"/>
	</bean>
	
	<!-- 定義視圖文件解析 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="${web.view.prefix}"/>
		<property name="suffix" value="${web.view.suffix}"/>
	</bean>
	
	<!-- 對靜態資源文件的訪問, 將無法mapping到Controller的path交給default servlet handler處理 -->
	<mvc:default-servlet-handler />
	
	<!-- 靜態資源映射  SpringMVC會自動給靜態資源Response添加緩存頭Cache-Control和Expires值 cache-period="31536000"-->
    <mvc:resources mapping="/static/**" location="/static/" />
	
	<!-- 定義無Controller的path<->view直接映射(首頁或者登陸頁) -->
	<mvc:view-controller path="/" view-name="redirect:${web.view.login}"/>

</beans>

config.properties

#============================#
#===== System settings ======#
#============================#

#產品信息設置
productName=科幫網  srping session
copyrightYear=2017
version=V1.0.0

#分頁配置
page.pageSize=10
#索引頁路徑
web.view.index=/index
#登陸頁面
web.view.login=/login
#視圖文件存放路徑
web.view.prefix=/WEB-INF/views/

web.view.suffix=.jsp

#靜態文件后綴
web.staticFile=.css,.js,.png,.jpg,.gif,.jpeg,.bmp,.ico,.swf,.psd,.htc,.htm,.html,.crx,.xpi,.exe,.ipa,.apk

spring-redis.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd" default-autowire="byName" default-lazy-init="true">
        
        <!-- 加載資源文件  其中包含變量信息,必須在Spring配置文件的最前面加載,即第一個加載-->
        <context:property-placeholder location="classpath:redis.properties" />
        <!-- redis -->
		<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"/>
		
		<bean id="jedisConnectionFactory"
		    class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
		    <property name="hostName" value="${redis.host}" />
		    <property name="port" value="${redis.port}" />
		    <property name="password" value="${redis.password}" />
		    <property name="timeout" value="${redis.timeout}" />
		    <property name="poolConfig" ref="jedisPoolConfig" />
		    <property name="usePool" value="true" />
		</bean>
		 
		<bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
		    <property name="connectionFactory" ref="jedisConnectionFactory" />
		</bean>
		 
		<!-- 將session放入redis -->
	    <context:annotation-config/>
		<bean id="redisHttpSessionConfiguration" class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration">
		    <property name="maxInactiveIntervalInSeconds" value="1800" />
		</bean>
</beans>

redis.properties

#redis中心 
redis.host=127.0.0.1
redis.port=6379
redis.password=123456
redis.maxIdle=100 
redis.maxActive=300 
redis.maxWait=1000 
redis.testOnBorrow=true 
redis.timeout=100000

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	<display-name>spring_session</display-name>
	<context-param>
	    <param-name>contextConfigLocation</param-name>
	    <param-value>classpath:spring-redis.xml</param-value>
    </context-param>
    <!-- spring session -->
    <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>
	</filter-mapping>
    <listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<servlet>
		<servlet-name>springServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath*:/spring-mvc*.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>springServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
    <welcome-file-list>
      <welcome-file>login</welcome-file>
    </welcome-file-list>
</web-app>

測試功能

最后,啟動項目訪問http://localhost:8080/spring_session/login

1.png
登錄redis服務,執行以下命令:

KEYS *

123.png

注意,對比sessionId是一致的。

網上很多同學,啟動的時候找不到 springSessionRepositoryFilter,注意在spring-redis.xml加入context:annotation-config/ 配置即可。

參考:http://docs.spring.io/spring-session/docs/current/reference/html5/

原文:http://blog.52itstyle.com/archives/759/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM