前言
通常在web开发中,会话管理是很重要的一部分,用于存储与用户相关的一些数据。对于JAVA开发者来说,项目中的session一般由Tomcat或者jetty容器来管理。
特点介绍
尽管使用特定的容器可以很好地实现会话管理,但是独立容器挂掉或者由于其他原因重启会导致用户信息丢失,并且无法支持分布式集群会话管理。
这是一个简单的负载均衡集群架构模型,后端三台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