Spring-Session分布式集群会话管理

架构设计之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包:

   
   
  1. <dependency>
  2. <groupId>org.springframework.session</groupId>
  3. <artifactId>spring-session-data-redis</artifactId>
  4. <version>1.2.2.RELEASE</version>
  5. </dependency>

spring-mvc.xml

   
   
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  5. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
  6. http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
  7. <description>Spring MVC Configuration</description>
  8. <!-- 加载配置属性文件 -->
  9. <context:property-placeholder ignore-unresolvable="true" location="classpath:config.properties" />
  10. <!-- 使用Annotation自动注册Bean,只扫描@Controller -->
  11. <context:component-scan base-package="com.itstyle.web" use-default-filters="false"><!-- base-package 如果多个,用“,”分隔 -->
  12. <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
  13. </context:component-scan>
  14. <mvc:annotation-driven/>
  15. <!--启动Spring MVC的注解功能,设置编码方式,防止乱码-->
  16. <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
  17. <property name="messageConverters">
  18. <list>
  19. <bean class = "org.springframework.http.converter.StringHttpMessageConverter">
  20. <property name = "supportedMediaTypes">
  21. <list>
  22. <value>text/html;charset=UTF-8</value>
  23. </list>
  24. </property>
  25. </bean>
  26. </list>
  27. </property>
  28. </bean>
  29. <!-- REST中根据URL后缀自动判定Content-Type及相应的View -->
  30. <bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
  31. <property name="mediaTypes" >
  32. <map>
  33. <entry key="xml" value="application/xml"/>
  34. <entry key="json" value="application/json"/>
  35. </map>
  36. </property>
  37. <property name="ignoreAcceptHeader" value="true"/>
  38. <property name="favorPathExtension" value="true"/>
  39. </bean>
  40. <!-- 定义视图文件解析 -->
  41. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  42. <property name="prefix" value="${web.view.prefix}"/>
  43. <property name="suffix" value="${web.view.suffix}"/>
  44. </bean>
  45. <!-- 对静态资源文件的访问, 将无法mapping到Controller的path交给default servlet handler处理 -->
  46. <mvc:default-servlet-handler />
  47. <!-- 静态资源映射 SpringMVC会自动给静态资源Response添加缓存头Cache-Control和Expires值 cache-period="31536000"-->
  48. <mvc:resources mapping="/static/**" location="/static/" />
  49. <!-- 定义无Controller的path<->view直接映射(首页或者登陆页) -->
  50. <mvc:view-controller path="/" view-name="redirect:${web.view.login}"/>
  51. </beans>

config.properties

   
   
  1. #============================#
  2. #===== System settings ======#
  3. #============================#
  4. #产品信息设置
  5. productName=科帮网 srping session
  6. copyrightYear=2017
  7. version=V1.0.0
  8. #分页配置
  9. page.pageSize=10
  10. #索引页路径
  11. web.view.index=/index
  12. #登陆页面
  13. web.view.login=/login
  14. #视图文件存放路径
  15. web.view.prefix=/WEB-INF/views/
  16. web.view.suffix=.jsp
  17. #静态文件后缀
  18. web.staticFile=.css,.js,.png,.jpg,.gif,.jpeg,.bmp,.ico,.swf,.psd,.htc,.htm,.html,.crx,.xpi,.exe,.ipa,.apk

spring-redis.xml

   
   
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
  4. xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  6. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
  7. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
  8. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd" default-autowire="byName" default-lazy-init="true">
  9. <!-- 加载资源文件 其中包含变量信息,必须在Spring配置文件的最前面加载,即第一个加载-->
  10. <context:property-placeholder location="classpath:redis.properties" />
  11. <!-- redis -->
  12. <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"/>
  13. <bean id="jedisConnectionFactory"
  14. class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
  15. <property name="hostName" value="${redis.host}" />
  16. <property name="port" value="${redis.port}" />
  17. <property name="password" value="${redis.password}" />
  18. <property name="timeout" value="${redis.timeout}" />
  19. <property name="poolConfig" ref="jedisPoolConfig" />
  20. <property name="usePool" value="true" />
  21. </bean>
  22. <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
  23. <property name="connectionFactory" ref="jedisConnectionFactory" />
  24. </bean>
  25. <!-- 将session放入redis -->
  26. <context:annotation-config/>
  27. <bean id="redisHttpSessionConfiguration" class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration">
  28. <property name="maxInactiveIntervalInSeconds" value="1800" />
  29. </bean>
  30. </beans>

redis.properties

   
   
  1. #redis中心
  2. redis.host=127.0.0.1
  3. redis.port=6379
  4. redis.password=123456
  5. redis.maxIdle=100
  6. redis.maxActive=300
  7. redis.maxWait=1000
  8. redis.testOnBorrow=true
  9. redis.timeout=100000

web.xml

   
   
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <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">
  3. <display-name>spring_session</display-name>
  4. <context-param>
  5. <param-name>contextConfigLocation</param-name>
  6. <param-value>classpath:spring-redis.xml</param-value>
  7. </context-param>
  8. <!-- spring session -->
  9. <filter>
  10. <filter-name>springSessionRepositoryFilter</filter-name>
  11. <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  12. </filter>
  13. <filter-mapping>
  14. <filter-name>springSessionRepositoryFilter</filter-name>
  15. <url-pattern>/*</url-pattern>
  16. </filter-mapping>
  17. <listener>
  18. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  19. </listener>
  20. <filter>
  21. <filter-name>encodingFilter</filter-name>
  22. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  23. <init-param>
  24. <param-name>encoding</param-name>
  25. <param-value>UTF-8</param-value>
  26. </init-param>
  27. <init-param>
  28. <param-name>forceEncoding</param-name>
  29. <param-value>true</param-value>
  30. </init-param>
  31. </filter>
  32. <filter-mapping>
  33. <filter-name>encodingFilter</filter-name>
  34. <url-pattern>/*</url-pattern>
  35. </filter-mapping>
  36. <servlet>
  37. <servlet-name>springServlet</servlet-name>
  38. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  39. <init-param>
  40. <param-name>contextConfigLocation</param-name>
  41. <param-value>classpath*:/spring-mvc*.xml</param-value>
  42. </init-param>
  43. <load-on-startup>1</load-on-startup>
  44. </servlet>
  45. <servlet-mapping>
  46. <servlet-name>springServlet</servlet-name>
  47. <url-pattern>/</url-pattern>
  48. </servlet-mapping>
  49. <welcome-file-list>
  50. <welcome-file>login</welcome-file>
  51. </welcome-file-list>
  52. </web-app>

测试功能

最后,启动项目访问http://localhost:8080/spring_session/login

1.png
登录redis服务,执行以下命令:

   
   
  1. KEYS *

123.png

注意,对比sessionId是一致的。

网上很多同学,启动的时候找不到 springSessionRepositoryFilter,注意在spring-redis.xml加入 配置即可。

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值