在Web项目开发中,会话管理是一个很重要的部分,用于存储与用户相关的数据。通常是由符合session规范的容器来负责存储管理,也就是一旦容器关闭,重启会导致会话失效。因此打造一个高可用性的系统,必须将session管理从容器中独立出来。而这实现方案有很多种,下面简单介绍下(仅限目前自己已知的):
第一种:使用硬件F5做粘性会话(不会,只是知道可以这么干),成本太高,后期也不好维护。
第二种:使用Nginx的ip_hash特性做粘性会话,可以让用户每次访问都转发到该用户第一次访问的web容器上,但是当该web容器上的应用挂了,nginx不会将该用户的请求转发到别的web容器,体验不好。
第三种:基于cookie实现,将session直接存储到cookie中(安全问题,虽然可以加密存储,但是觉得不能将敏感数据放在客户端)
第四种:使用容器扩展来实现,大家比较容易接受的是通过容器插件来实现,比如基于Tomcat的memcached-session-manager / tomcat-redis-session-manager,基于Jetty的jetty-nosql-memcache / jetty-session-redis等等。好处是对项目来说是透明的,无需改动代码。不过前者目前还不支持Tomcat 8,或者说不太完善。此方法过于依赖容器,一旦容器升级或者更换意味着又得从新来过。并且代码不在项目中,对开发者来说维护也是个问题(如果你使用的是weblogic、jboss、websphere等商业web容器,根本没有这种第三方容器扩展,web容器换了厂商就不行了)。
第五种:自己实现一套会话管理,将session读取/存储到Redis或其他nosql或数据库(网站用户量大的情况下,频繁dml数据,对db压力大)中。很显然这个方案灵活性最大,但开发需要一些额外的时间。弄懂了会挺不错的。
第六种:使用框架的会话管理工具spring-session,可以理解是替换了Servlet那一套会话管理,既不依赖容器,又不需要改动代码,并且是用了spring-data-redis那一套连接池,可以说是最完美的解决方案。当然,前提是项目要使用Spring Framework才行。
第七种:如果项目中使用shiro这种自带session(非httpsession)的权限框架,需要重写shiro的SessionDao将session存入redis(或其他)来实现session共享,可以自己重写(也不是很麻烦)或者找现成的(shiro-redis微笑脸,省的自己造轮子了,知道原理就行)。
前三种方案:出于安全、成本(自己搞着玩不好弄)、无法完全做到724365不宕机,个人不推荐。有兴趣的自己研究吧。
剩下的四种方案大体思路其实都一样,存到nosql中(内存读写快啊)。
各方案具体实现思路:
第四种:
直接去这几个插件github地址,人家写的使用方法更全,不在赘述。(看了点redis-session-manager的源码,他是将自定义了一个RedisSession类继承StandardSession类,这个类是tomcat中lib下的类,太依赖容器了,获取session信息从redis中序列化/反序列化出来)
第五种:(参考别人博客,内容直接粘贴过来了,地址在最上面)
要实现将session信息存入redis,总结了下大概是三点: 1.实现httpsession接口,重写我们需要用到的方法,比如set get这些。。balabala一堆...... 2.继承HttpServletRequestWrapper,这个类里面有getSession()方法,我们需要重写,来取自定义session 3.实现filter,用来拦截客户端请求,获取我们自定义的request,从而获得session
具体实现(这个人并没有实现从redis中读取session的操作,需要将request中获取session和产生session都加入redis操作,但是这里的思路需要掌握,很受教,自己想要实现完美挺难的): 1.实现httpsession接口
public class HttpSessionWrapper implements HttpSession {protected final Logger logger = LoggerFactory.getLogger(getClass());private String sid = "";private HttpServletRequest request;private HttpServletResponse response;private final long creationTime = System.currentTimeMillis();private final long lastAccessedTime = System.currentTimeMillis();private SessionMeta meta;public HttpSessionWrapper() {}public HttpSessionWrapper(String sid,SessionMeta meta, HttpServletRequest request,HttpServletResponse response) {this.sid=sid;this.request=request;this.response=response;this.meta=meta;}public Object getAttribute(String name) {logger.info(getClass()+"getAttribute(),name:"+name);Jedis jedis =null;Object obj =null;String jsonStr = null;try {jedis =JedisPoolStore.getInstance().getJedis(meta.getHost(), meta.getPort());jsonStr = jedis.get(name);if(jsonStr!=null||StringUtils.isNotEmpty(jsonStr)){jedis.expire(name, meta.getSeconds());// 重置过期时间obj =JSON.parseObject(jsonStr, User.class); //反序列对象}if (jedis != null) {JedisPoolStore.getInstance().returnJedis(jedis);}return obj;}catch (JSONException je) {logger.error(je.getMessage());if (null != jedis)JedisPoolStore.getInstance().returnJedis(jedis);return jsonStr;}catch (Exception e) {logger.error(e.getMessage());if (e instanceof JedisException) {if (null != jedis)JedisPoolStore.getInstance().returnBrokenJedis(jedis);} else {if (null != jedis)JedisPoolStore.getInstance().returnJedis(jedis);}throw new HttpSessionException(" session 异常 getAttribute() name:"+name);}}public void setAttribute(String name, Object value) {logger.info(getClass()+"setAttribute(),name:"+name);Jedis jedis =null;try {jedis =JedisPoolStore.getInstance().getJedis(meta.getHost(), meta.getPort());if(value instanceof String){String value_ =(String) value;jedis.set(name,value_);//普通字符串对象}else{jedis.set(name, JSON.toJSONString(value));//序列化对象}jedis.expire(name, meta.getSeconds());// 重置过期时间if (jedis != null) {JedisPoolStore.getInstance().returnJedis(jedis);}} catch (Exception e) {logger.error(e.getMessage());if (e instanceof JedisException) {if (null != jedis)JedisPoolStore.getInstance().returnBrokenJedis(jedis);} else {if (null != jedis)JedisPoolStore.getInstance().returnJedis(jedis);}throw new HttpSessionException(" session 异常 setAttribute() name:"+name+",value:"+value);}}/*** 不可用* @deprecated**/public void invalidate() {logger.info(getClass()+"invalidate()");}public void removeAttribute(String name) {logger.info(getClass()+"removeAttribute(),name:"+name);if(StringUtils.isNotEmpty(name)){Jedis jedis =null;try {jedis =JedisPoolStore.getInstance().getJedis(meta.getHost(), meta.getPort());jedis.del(name);if (jedis != null) {JedisPoolStore.getInstance().returnJedis(jedis);}} catch (Exception e) {logger.error(e.getMessage());if (e instanceof JedisException) {if (null != jedis)JedisPoolStore.getInstance().returnBrokenJedis(jedis);} else {if (null != jedis)JedisPoolStore.getInstance().returnJedis(jedis);}throw new HttpSessionException(" session 异常 removeAttribute() name:"+name);}}}/*** 不可用* @deprecated**/public Object getValue(String name) {return null;}/*** 不可用* @deprecated**/public Enumeration getAttributeNames() {return null;}/*** 不可用* @deprecated**/public String[] getValueNames() {return null;}/*** 不可用* @deprecated**/public void putValue(String name, Object value) {}/*** 不可用* @deprecated**/public void removeValue(String name) {}public long getCreationTime() {return creationTime;}public String getId() {logger.info(getClass()+"getId():"+sid);return sid;}public long getLastAccessedTime() {return lastAccessedTime;}/*** 不可用* @deprecated**/public ServletContext getServletContext() {return null;}/*** 不可用* @deprecated**/public void setMaxInactiveInterval(int interval) {}/*** 不可用* @deprecated**/public int getMaxInactiveInterval() {return 0;}/*** 不可用* @deprecated**/public HttpSessionContext getSessionContext() {return null;}/*** 不可用* @deprecated**/public boolean isNew() {logger.info(getClass()+"isNew()");return false;}}
2.继承HttpServletRequestWrapper
/***** @author xiaoshuai**/public class DefinedHttpServletRequestWrapper extends HttpServletRequestWrapper{protected final Logger logger = LoggerFactory.getLogger(getClass());private HttpSessionWrapper currentSession;private HttpServletRequest request;private HttpServletResponse response;private String sid = "";private SessionMeta meta;public DefinedHttpServletRequestWrapper(HttpServletRequest request) {super(request);}public DefinedHttpServletRequestWrapper(String sid, HttpServletRequest request) {super(request);this.sid = sid;}public DefinedHttpServletRequestWrapper(String sid, SessionMeta meta,HttpServletRequest request,HttpServletResponse response) {super(request);this.request = request;this.response = response;this.sid = sid;this.meta=meta;}@Overridepublic HttpSession getSession(boolean create) {if(currentSession != null) {return currentSession;}if(!create) {return null;}currentSession = new HttpSessionWrapper(sid,meta, request, response);return currentSession;}@Overridepublic HttpSession getSession() {return getSession(true);}}
3.实现filter
public class SessionFilter implements Filter{protected final Logger logger = LoggerFactory.getLogger(getClass());private static SessionMeta meta = new SessionMeta();private static final String host ="host";private static final String port ="port";private static final String seconds="seconds";public void init(FilterConfig filterConfig) throws ServletException {logger.debug("init filterConfig info");meta.setHost(filterConfig.getInitParameter(host));meta.setPort(Integer.parseInt(filterConfig.getInitParameter(port)));meta.setSeconds(Integer.parseInt(filterConfig.getInitParameter(seconds)));}public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {//从cookie中获取sessionId,如果此次请求没有sessionId,重写为这次请求设置一个sessionIdHttpServletRequest httpRequest = (HttpServletRequest) request;HttpServletResponse httpResponse = (HttpServletResponse) response;String sid = CookieHelper.findCookieInfo(httpRequest,CookieHelper.COOKIE_DOMAIN_NAME);if(StringUtils.isEmpty(sid) ){try {sid =CookieHelper.saveCookie(SessionId.doIds(), httpResponse);} catch (Exception e) {e.printStackTrace();}}logger.info("JESSIONID:"+sid);chain.doFilter(new DefinedHttpServletRequestWrapper(sid,meta,httpRequest, httpResponse), response);}public void destroy() {}}
4.配置web.xml
<!-- session过滤器 --><filter><filter-name>sessionFilter</filter-name><filter-class>cn.session.filter.SessionFilter</filter-class><init-param><param-name>host</param-name><param-value>10.1.193.1</param-value></init-param><init-param><param-name>port</param-name><param-value>6372</param-value></init-param><init-param><param-name>seconds</param-name><param-value>1800</param-value></init-param></filter><filter-mapping><filter-name>sessionFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping>
第六种:(没用过,感觉这个人的挺靠谱,直接粘贴过来了,参考博客的地址也在最上面)
这里简单记录下整合的过程:如果项目之前没有整合过spring-data-redis的话,这一步需要先做,在maven中添加这两个依赖:<dependency><groupId>org.springframework.data</groupId><artifactId>spring-data-redis</artifactId><version>1.5.2.RELEASE</version></dependency><dependency><groupId>org.springframework.session</groupId><artifactId>spring-session</artifactId><version>1.0.2.RELEASE</version></dependency>再在applicationContext.xml中添加以下bean,用于定义redis的连接池和初始化redis模版操作类,自行替换其中的相关变量。<!-- redis --><bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"></bean><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.pass}" /><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 --><bean id="redisHttpSessionConfiguration" class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"><property name="maxInactiveIntervalInSeconds" value="1800" /></bean>这里前面几个bean都是操作redis时候使用的,最后一个bean才是spring-session需要用到的,其中的id可以不写或者保持不变,这也是一个约定优先配置的体现。这个bean中又会自动产生多个bean,用于相关操作,极大的简化了我们的配置项。其中有个比较重要的是springSessionRepositoryFilter,它将在下面的代理filter中被调用到。maxInactiveIntervalInSeconds表示超时时间,默认是1800秒。写上述配置的时候我个人习惯采用xml来定义,官方文档中有采用注解来声明一个配置类。然后是在web.xml中添加一个session代理filter,通过这个filter来包装Servlet的getSession()。需要注意的是这个filter需要放在所有filter链最前面。<!-- delegatingFilterProxy --><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>这样便配置完毕了,需要注意的是,spring-session要求Redis Server版本不低于2.8。验证:使用redis-cli就可以查看到session key了,且浏览器Cookie中的jsessionid已经替换为session。127.0.0.1:6379> KEYS *1) "spring:session:expirations:1440922740000"2) "spring:session:sessions:35b48cb4-62f8-440c-afac-9c7e3cfe98d3"
第七种:如果项目中用到shiro了,shiro是不带将session持久化到redis实现集群共享的,所以说需要自己实现或者找别人写好的,下面来说说自己实现,不管别人写还是自己实现思路都是一样的,了解了岂不是更好。(这个自己项目确实遇到这个问题了,通过网上的资料已经解决,参考的太多就不贴地址了,只说自己怎么弄的)
配置shiro的xml<!-- SessionManager --><bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager"><!-- session存储的实现(此处为自己重写的sessionDao) --><property name="sessionDAO" ref="redisSessionDAO" /><!-- 定时清理失效会话, 清理用户直接关闭浏览器造成的孤立会话 --><property name="sessionValidationInterval" value="1800000"/><property name="sessionValidationSchedulerEnabled" value="true"/><property name="sessionIdCookie" ref="sessionIdCookie"/><property name="sessionIdCookieEnabled" value="true"/></bean>
RedisSessionDao
public class RedisSessionDao extends AbstractSessionDAO {private static Logger logger = LoggerFactory.getLogger(RedisSessionDao.class);/** The Redis key prefix for the sessions*/private static final String REDIS_SHIRO_SESSION = "shiro_redis_session:";private static final Integer SESSION_VAL_TIME_SPAN = 18000;/*** redis接口*/@Resource(name = "cacheServiceImpl")private ICacheService iCacheService;/*** @discription 创建session,保存到数据库** @param session* @return** @author zhaoqiang* @created 2017年3月3日 下午1:28:09*/@Overrideprotected Serializable doCreate(Session session) {Serializable sessionId = this.generateSessionId(session);this.assignSessionId(session, sessionId);saveSession(session);return sessionId;}/*** @discription 获取session** @param sessionId* @return** @author zhaoqiang* @created 2017年3月3日 下午1:28:43*/@Overrideprotected Session doReadSession(Serializable sessionId) {if (sessionId == null) {throw new NullPointerException("session id is empty");}SimpleSession session = null;try {byte[] value = iCacheService.getByte(buildRedisSessionKey(sessionId));session = SerializeUtil.unserialize(value, SimpleSession.class);} catch (Exception e) {e.printStackTrace();logger.error("get session error");}return session;}/*** @discription 更新session的最后一次访问时间** @param session** @author zhaoqiang* @created 2017年3月3日 下午1:34:24*/@Overridepublic void update(Session session) {saveSession(session);}/*** @discription 删除session** @param session** @author zhaoqiang* @created 2017年3月3日 下午1:35:48*/@Overridepublic void delete(Session session) {if (session == null) {logger.error("session can not be null,delete failed");return;}Serializable id = session.getId();if (id == null) {throw new NullPointerException("session id is empty");}try {iCacheService.delByString(buildRedisSessionKey(id));} catch (Exception e) {e.printStackTrace();logger.error("delete session error");}}/*** @discription 获得活跃的session集合** @return** @author zhaoqiang* @created 2017年3月3日 下午2:05:22*/@Overridepublic Collection<Session> getActiveSessions() {Set<Session> sessions = new HashSet<Session>();try {Set<String> keys = iCacheService.keys(REDIS_SHIRO_SESSION);if (keys == null || keys.size() == 0) {return sessions;}for (String key : keys) {Session s = null;try {s = iCacheService.getObject(key, SimpleSession.class);} catch (ClassNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}sessions.add(s);}} catch (Exception e) {logger.error("[获得活跃的session集合(getActiveSessions)-error][" + e.getMessage() + "]");e.printStackTrace();}return sessions;}/*** @discription 处理缓存中id名称** @param sessionId* @return** @author zhaoqiang* @created 2017年3月9日 下午1:13:45*/private String buildRedisSessionKey(Serializable sessionId) {return REDIS_SHIRO_SESSION + sessionId;}/*** @discription 持久化session到redis** @param session** @author zhaoqiang* @created 2017年3月9日 下午1:06:53*/private void saveSession(Session session) {if (session == null || session.getId() == null) {throw new NullPointerException("session is empty");}try {String key = buildRedisSessionKey(session.getId());long sessionTimeOut = session.getTimeout() / 1000;Long expireTime = sessionTimeOut + SESSION_VAL_TIME_SPAN + (5 * 60);iCacheService.setObject(key, session, new Integer(expireTime.toString()));} catch (Exception e) {e.printStackTrace();logger.error("save session error");}}}
public class HttpSessionWrapper implements HttpSession {
protected final Logger logger = LoggerFactory.getLogger(getClass());
private String sid = "";
private HttpServletRequest request;
private HttpServletResponse response;
private final long creationTime = System.currentTimeMillis();
private final long lastAccessedTime = System.currentTimeMillis();
private SessionMeta meta;
public HttpSessionWrapper() {
}
public HttpSessionWrapper(String sid,SessionMeta meta, HttpServletRequest request,
HttpServletResponse response) {
this.sid=sid;
this.request=request;
this.response=response;
this.meta=meta;
}
public Object getAttribute(String name) {
logger.info(getClass()+"getAttribute(),name:"+name);
Jedis jedis =null;
Object obj =null;
String jsonStr = null;
try {
jedis =JedisPoolStore.getInstance().getJedis(meta.getHost(), meta.getPort());
jsonStr = jedis.get(name);
if(jsonStr!=null||StringUtils.isNotEmpty(jsonStr)){
jedis.expire(name, meta.getSeconds());// 重置过期时间
obj =JSON.parseObject(jsonStr, User.class); //反序列对象
}
if (jedis != null) {
JedisPoolStore.getInstance().returnJedis(jedis);
}
return obj;
}
catch (JSONException je) {
logger.error(je.getMessage());
if (null != jedis)
JedisPoolStore.getInstance().returnJedis(jedis);
return jsonStr;
}
catch (Exception e) {
logger.error(e.getMessage());
if (e instanceof JedisException) {
if (null != jedis)
JedisPoolStore.getInstance().returnBrokenJedis(jedis);
} else {
if (null != jedis)
JedisPoolStore.getInstance().returnJedis(jedis);
}
throw new HttpSessionException(" session 异常 getAttribute() name:"+name);
}
}
public void setAttribute(String name, Object value) {
logger.info(getClass()+"setAttribute(),name:"+name);
Jedis jedis =null;
try {
jedis =JedisPoolStore.getInstance().getJedis(meta.getHost(), meta.getPort());
if(value instanceof String){
String value_ =(String) value;
jedis.set(name,value_);//普通字符串对象
}else{
jedis.set(name, JSON.toJSONString(value));//序列化对象
}
jedis.expire(name, meta.getSeconds());// 重置过期时间
if (jedis != null) {
JedisPoolStore.getInstance().returnJedis(jedis);
}
} catch (Exception e) {
logger.error(e.getMessage());
if (e instanceof JedisException) {
if (null != jedis)
JedisPoolStore.getInstance().returnBrokenJedis(jedis);
} else {
if (null != jedis)
JedisPoolStore.getInstance().returnJedis(jedis);
}
throw new HttpSessionException(" session 异常 setAttribute() name:"+name+",value:"+value);
}
}
/**
\* 不可用
\* @deprecated
\*
*/
public void invalidate() {
logger.info(getClass()+"invalidate()");
}
public void removeAttribute(String name) {
logger.info(getClass()+"removeAttribute(),name:"+name);
if(StringUtils.isNotEmpty(name)){
Jedis jedis =null;
try {
jedis =JedisPoolStore.getInstance().getJedis(meta.getHost(), meta.getPort());
jedis.del(name);
if (jedis != null) {
JedisPoolStore.getInstance().returnJedis(jedis);
}
} catch (Exception e) {
logger.error(e.getMessage());
if (e instanceof JedisException) {
if (null != jedis)
JedisPoolStore.getInstance().returnBrokenJedis(jedis);
} else {
if (null != jedis)
JedisPoolStore.getInstance().returnJedis(jedis);
}
throw new HttpSessionException(" session 异常 removeAttribute() name:"+name);
}
}
}
/**
\* 不可用
\* @deprecated
\*
*/
public Object getValue(String name) {
return null;
}
/**
\* 不可用
\* @deprecated
\*
*/
public Enumeration getAttributeNames() {
return null;
}
/**
\* 不可用
\* @deprecated
\*
*/
public String[] getValueNames() {
return null;
}
/**
\* 不可用
\* @deprecated
\*
*/
public void putValue(String name, Object value) {
}
/**
\* 不可用
\* @deprecated
\*
*/
public void removeValue(String name) {
}
public long getCreationTime() {
return creationTime;
}
public String getId() {
logger.info(getClass()+"getId():"+sid);
return sid;
}
public long getLastAccessedTime() {
return lastAccessedTime;
}
/**
\* 不可用
\* @deprecated
\*
*/
public ServletContext getServletContext() {
return null;
}
/**
\* 不可用
\* @deprecated
\*
*/
public void setMaxInactiveInterval(int interval) {
}
/**
\* 不可用
\* @deprecated
\*
*/
public int getMaxInactiveInterval() {
return 0;
}
/**
\* 不可用
\* @deprecated
\*
*/
public HttpSessionContext getSessionContext() {
return null;
}
/**
\* 不可用
\* @deprecated
\*
*/
public boolean isNew() {
logger.info(getClass()+"isNew()");
return false;
}
}