`
yxkelsey
  • 浏览: 39009 次
  • 性别: Icon_minigender_1
  • 来自: 青岛
社区版块
存档分类
最新评论

Web应用HTTP Session共享方案

    博客分类:
  • java
阅读更多
在构建能够灵活地进行水平扩展、高可用性的Java Web应用程序时候,对http session的处理策略很大程度决定了应用程序的扩展性、可用性。一般而言对http session有如下的处理方案:
1、在服务器端不保存Session,完全无状态

     对于不需要保持用户状态的Web应用,采用Stateless是最为恰当的,因此就不存在Session共享的问题。REST (Representational State Transfer) 算是最为典型的例子。
2、基于浏览器 Cookie的Session共享

      此种方案把用户相关的Session信息存储到浏览器的Cookie中,也称为客户端Session。

      采用Flash Cookie、URL重写的方式传递Session信息的方案也可以归为此类。

      缺点:只能够存储字符串、数值等基本类型的数据;Cookie大小存在限制;安全性;带宽及数据解压缩、网络传输性能问题。
3、基于数据库的Session共享,实现分布式应用间Session共享

     此种方案把Session信息存储到数据库表,这样实现不同应用服务器间Session信息的共享。诸如Websphere Portal、Weblogic Portal都采用了类似的方案。

     Tomcat Persistent Manager 的JDBC Based Store 提供了类似实现机制,表结构如下:

        create table tomcat_sessions (
            session_id     varchar(100) not null primary key,
            valid_session  char(1) not null,
            max_inactive   int not null,
            last_access    bigint not null,
            app_name       varchar(255),
            session_data   mediumblob,
            KEY kapp_name(app_name)
          );

        优点:实现简单

        缺点:由于数据库服务器相对于应用服务器更难扩展且资源更为宝贵,在高并发的Web应用中,最大的性能瓶颈通常在于数据库服务器。因此如果将 Session存储到数据库表,频繁的增加、删除、查询操作很容易造成数据库表争用及加锁,最终影响业务。


4、基于应用服务器/Servlet容器的Clustering机制

        一些常用的应用服务器及Servlet容器的Clustering机制可以实现Session Replication的功能,例如Tomcat Clustering/Session Replication、Jboss buddy replication。

         缺点:基于Clustering的Session复制性能很差,扩展性也很不行。
5、基于 NFS的Session共享

         通过NFS方式来实现各台服务器间的Session共享,各台服务器只需要mount共享服务器的存储Session的磁盘即可,实现较为简单。但NFS 对高并发读写的性能并不高,在硬盘I/O性能和网络带宽上存在较大瓶颈,尤其是对于Session这样的小文件的频繁读写操作。

        基于磁盘阵列/SAN/NAS等共享存储的方案道理也类似。
6、基于Terracotta、Ehcache、 JBossCache等Java Caching方案实现Session共享

    如果系统架构是Java体系,可以考虑采用Terracotta、Ehcache、JbossCache、Oscache等Java Caching方案来实现Session 共享。

    缺点:架构用于非java体系很不方便;对于是诸如静态页面之类的缓存,采用Memcached的方案比Java更为高效
7、基于Memcached/Tokyo Tyrant 等Key-Value DB的Session共享

    整体说来此种方案扩展性最好,推荐使用。

    原理:Tomcat 服务器提供了org.apache.catalina.session.StandardManager 和org.apache.catalina.session.PersistentManager用于Session对象的管理,可以自定义 PersistentManager的

Store 类来实现自己Memcached、Tokyo Tyrant、Redis等Key-Value DB的客户端。

    以Memcached的客户端为例(摘自Use MemCacheStore in Tomcat):

package com.yeeach;

import com.danga.MemCached.MemCachedClient;

import com.danga.MemCached.SockIOPool;

public class MemCacheStore extends StoreBase implements Store {

/**
* The descriptive information about this implementation.
*/
protected static String info = "MemCacheStore/1.0";

/**
* The thread safe and thread local memcacheclient instance.
*/
private static final ThreadLocal<MemCachedClient> memclient = new ThreadLocal<MemCachedClient>();

/**
* The server list for memcache connections.
*/
private List<String> servers = new ArrayList<String>();

/**
* all keys for current request session.
*/
private List<String> keys = Collections
.synchronizedList(new ArrayList<String>());

/**
* Return the info for this Store.
*/
public String getInfo() {
return (info);
}

/**
* Clear all sessions from the cache.
*/
public void clear() throws IOException {
getMemcacheClient().flushAll();
keys.clear();
}

/**
* Return local keyList size.
*/
public int getSize() throws IOException {
return getKeyList().size();
}

/**
* Return all keys
*/
public String[] keys() throws IOException {
return getKeyList().toArray(new String[] {});
}

/**
* Load the Session from the cache with given sessionId.
*
*/
public Session load(String sessionId) throws ClassNotFoundException,
IOException {

try {

byte[] bytes = (byte[]) getMemcacheClient().get(sessionId);
if (bytes == null)
return null;
ObjectInputStream ois = bytesToObjectStream(bytes);

StandardSession session = (StandardSession) manager
.createEmptySession();
session.setManager(manager);
session.readObjectData(ois);
if (session.isValid() && !keys.contains(sessionId)) {
keys.add(sessionId);
}
return session;

} catch (Exception e) {
return (null);
}
}

/**
* transform a vaild Session from objectinputstream.
* Check which classLoader is responsible for the current instance.
*
* @param bytes
* @return ObjectInputStream with the Session object.
* @throws IOException
*/
private ObjectInputStream bytesToObjectStream(byte[] bytes)
throws IOException {
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = null;
Loader loader = null;
ClassLoader classLoader = null;
Container container = manager.getContainer();
if (container != null)
loader = container.getLoader();
if (loader != null)
classLoader = loader.getClassLoader();
if (classLoader != null)
ois = new CustomObjectInputStream(bais, classLoader);
else
ois = new ObjectInputStream(bais);
return ois;
}

/**
* remove the session with given sessionId
*/
public void remove(String sessionId) throws IOException {
getMemcacheClient().delete(sessionId);
List<String> keyList = getKeyList();
keyList.remove(sessionId);
}

/**
* Store a objectstream from the session into the cache.
*/
public void save(Session session) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
StandardSession standard = (StandardSession) session;
standard.writeObjectData(oos);
getMemcacheClient().add(session.getId(), baos.toByteArray());
Object ob = getMemcacheClient().get(session.getId());
List<String> keyList = getKeyList();
keyList.add(session.getId());
}

/**
*
* @return
*/
private List<String> getKeyList() {
return keys;
}

/**
* Simple instanc of the Memcache client and SockIOPool.
* @return memchacheclient
*/
private MemCachedClient getMemcacheClient() {
if (memclient == null) {

Integer[] weights = { 1 };
// grab an instance of our connection pool
SockIOPool pool = SockIOPool.getInstance();
if (!pool.isInitialized()) {
String[] serverlist = servers.toArray(new String[] {});
// set the servers and the weights
pool.setServers(serverlist);
pool.setWeights(weights);

// set some basic pool settings
// 5 initial, 5 min, and 250 max conns
// and set the max idle time for a conn
// to 6 hours
pool.setInitConn(5);
pool.setMinConn(5);
pool.setMaxConn(250);
pool.setMaxIdle(1000 * 60 * 60 * 6);

// set the sleep for the maint thread
// it will wake up every x seconds and
// maintain the pool size
pool.setMaintSleep(30);

// set some TCP settings
// disable nagle
// set the read timeout to 3 secs
// and don't set a connect timeout
pool.setNagle(false);
pool.setSocketTO(3000);
pool.setSocketConnectTO(0);

// initialize the connection pool
pool.initialize();
}

// lets set some compression on for the client
// compress anything larger than 64k

memclient.get().setCompressEnable(true);
memclient.get().setCompressThreshold(64 * 1024);
}
return memclient.get();
}

public List<String> getServers() {
return servers;
}

public void setServers(String serverList) {
StringTokenizer st = new StringTokenizer(serverList, ", ");
servers.clear();
while (st.hasMoreTokens()) {
servers.add(st.nextToken());
}
}

}

Tomcat 的配置文件:

<Context path="/test" docBase="test.war">
<Manager className="org.apache.catalina.session.PersistentManager"
distributable="true">
<Store className="com.yeeach.MemcachedStore"
servers="192.168.0.111:11211,192.168.0.112:11211" />
</Manager>

</Context>



    这里只是作为测试演示了在Tomcat中集成Memcached的实现方案。并没有考虑性能、高可用、Memcached 存储Session的持久化(可以使用Memcachedb实现)、Session管理等问题。

    针对Tomcat与Memcached集成有一个开源项目memcached-session-manager  功能实现相对完善,尤其是其设计思想值得借鉴。

    The memcached session manager installed in a tomcat holds all sessions locally in the own jvm, just like the StandardManager does it as well.

    Additionally, after a request was finished, the session (only if existing) is additionally sent to a memcached node for backup.

    When the next request for this session has to be served, the session is locally available and can be used, after this second request is finished the session is updated in the memcached node.



    对于采用Tokyo Tyrant、Redis等当下流行的Key-Value DB实现机制类似
分享到:
评论
1 楼 sucheng2016 2016-10-18  
        

相关推荐

    Asp.net中处理一个站点不同Web应用共享Session的问题

    2、问题原因: 一个WEB应用相当于一个站点,应用与应用之间不可能共享Session。3、解决方法:1) 将四个web应用包含在同一个解决方案中(注:调整.webinfo文件使解决方案能构正常运行)2) 新建一个web应用Main,...

    Tomcat实现session共享(session 会话复制)

    集群最有效的方案就是负载均衡,而实现负载均衡用户每一个请求都有可能被分配到不固定的服务器上,这样我们首先要解决session的统一来保证无论用户的请求被转发到哪个服务器上都能保证用户的正常使用,即需要实现...

    Nginx+Tomcat负载平衡,Redis管理session存储

    分布式web server集群部署后需要实现session共享,针对 tomcat 服务器的实现方案多种多样,比如 tomcat cluster session 广播、nginx IP hash策略、nginx sticky module等方案,本文主要介绍了使用 redis 服务器进行...

    tomcat共享多个web应用会话的实现方法

    tomcat共享多个web应用会话的实现方法 问题 今天有位朋友问了个问题,大致是:tomcat下两个Java web,一个是商城,一个是直播,从商城登录后,再跳转到直播,发现处于非登录状态。 解决思路 将session抽出来成一个...

    sna集中式session管理实现服务器集群及客户端程序

    sna集中式session管理实现服务器集群及客户端程序,以“单点登陆、session共享解决方案(2)”为基础建立的服务器机群应用,运行server.bat启动服务器端,将client包导入web工程,通过Client.sessionPut()等方法调用。...

    ASP.NET应用下基于SessionState的“状态编程框架”解决方案

    在一个基于ASP.NET的Web应用程序中,我们通常使用SessionState保存基于某个客户端的状态信息。但是这种单纯使用SessionState的编程方式具有很多局限,比如SessionItem的Key值冲突,比如没有一个有效的SessionState...

    Web应用的负载均衡、集群、高可用(HA)解决方案

    本文来自于csdn,本文主要介绍了7个相关的组件,关键概念及术语,常用Web集群方案,高可用(HA)和session共享等。——它是Apache软件基金会的一个开放源代码的跨平台的网页服务器,属于老牌的web服务器了,支持基于Ip...

    JWT-Json Web Token-目前最流行跨域身份验证解决方案

    如果需要进行服务集群则需要处理好共享session的问题。 如果一个庞大的系统需要按服务分解为多个独立的服务,使用分布式架构,不方便进行横向扩展,这种模式只适合于单体应用模式。如果需要进行服务集群则需要处理好...

    缓存还可以这么玩儿.pptx

    缓存包括Session 会话状态及应用横向扩展时的状态数据等,这类数据一般是难以恢复的,对可用性要求较高,多应用于高可用集群; 4) 并行处理.通常涉及大量中间计算结果需要共享; 5) 事件处理.分布式缓存提供了针对...

    ASP.NET4高级程序设计(第4版) 3/3

    8.2.1 Web应用程序和DataSet 250 8.2.2 XML集成 251 8.3 DataSet类 251 8.4 DataAdapter类 252 8.4.1 填充DataSet 253 8.4.2 使用多个表和关系 254 8.4.3 查找特定行 257 8.4.4 在数据访问类里使用...

    java-servlet-api.doc

    作为一个Servlet的开发者,你必须决定你的Web应用是否处理客户机不加入或不能加入Session。服务器会在Web服务器或Servlet规定的时间内维持一个Session对象。当Session终止时,服务器会释放Session对象以及所有绑定在...

    超级有影响力霸气的Java面试题大全文档

    多态性语言具有灵活、抽象、行为共享、代码共享的优势,很好的解决了应用程序函数同名问题。 5、String是最基本的数据类型吗?  基本数据类型包括byte、int、char、long、float、double、boolean和short。  java....

    红顶网络办公系统3.0

    10、集成网络硬盘组件,提供便捷的局域网、广域网文件共享方案 11、集成商业管理组件,轻松的管理客户、供应商资料和产品销售记录 12、集成内部邮件、即时短信、文件柜、聊天室、论坛等模块,提供企业内部信息交流...

    spring boot 实践学习案例,与其它组件整合

    - Spring Boot 缓存,包括redis、ehcache、spring-cache、memcached、使用redis实现session共享 等。 - springboot-templates - Spring Boot 模板,包括thymeleaf、freemarker、jsp、表单校验 等。 - ...

    asp.net知识库

    ASP.NET 2.0构建动态导航的Web应用程序(TreeView和Menu ) 体验.net2.0的优雅(3) -- 为您的 SiteMap 添加 控制转发功能 GridView控件使用经验 ASP.NET 2.0:弃用 DataGrid 吧,有新的网格控件了! ASP.NET2.0控件...

    万辰OA2·5正版企业美化版

    10、集成网络硬盘组件,提供便捷的局域网、广域网文件共享方案 11、集成商业管理组件,轻松的管理客户、供应商资料和产品销售记录 12、集成内部邮件、即时短信、文件柜、聊天室、论坛等模块,提供企业内部信息交流...

    万辰OA2.5正版企业美化版

    10、集成网络硬盘组件,提供便捷的局域网、广域网文件共享方案 11、集成商业管理组件,轻松的管理客户、供应商资料和产品销售记录 12、集成内部邮件、即时短信、文件柜、聊天室、论坛等模块,提供企业内部信息交流...

    ASP.NET4高级程序设计第4版 带目录PDF 分卷压缩包 part1

    8.2.1 Web应用程序和DataSet 8.2.2 XML集成 8.3 DataSet类 8.4 DataAdapter类 8.4.1 填充DataSet 8.4.2 使用多个表和关系 8.4.3 查找特定行 8.4.4 在数据访问类里使用DataSet 8.4.5 数据绑定 8.5...

Global site tag (gtag.js) - Google Analytics