美文网首页
集群共享Session

集群共享Session

作者: 米刀灵 | 来源:发表于2016-12-15 15:19 被阅读114次

客户端cookie加密
当用户登陆成功以后,把网站域名、用户名、密码、token、 session有效时间全部采用cookie的形式写入到客户端的cookie里面,如果用户从一台Web服务器跨越到另一台服务器的时候,我们的程序主动去检测客户端的cookie信息,进行判断,然后提供对应的服务,当然,如果cookie过期,或者无效,自然就不让用户继续服务了。

使用ip_hash等分配方法
nginx中负载均衡配置时,可以选择ip_hash算法,这样同一个IP的请求会定向到同一台后端,为了解决ip_hash的一些问题,可以使用upstream_hash这个第三方模块,这个模块多数情况下是用作url_hash的,但是并不妨碍将它用来做session共享。

使用数据库保存session
使用数据库来保存session,就算服务器宕机了也没事,session照样在。
每次请求都进行数据库读写开销不小(使用内存数据库可以提高性能,宕机就会丢失数据。可供选择的内存数据库有BerkeleyDB,Mysql的内存表);这个方式与NFS的方式类似,也是采用一台Mysql服务器做共享服务器,把所有的session的数据保存到Mysql服务器上,所有Web服务器都来这台Mysql服务器来获取Session 数据。缺点也是依赖性太强,Mysql无法工作了影响所有的Web服务器,当然,可以考虑副本集Mysql数据库来共享session。可以直接在tomcat和jetty配置文件中直接配置。下面以tomcat为例:

在conf/context.xml中文件中,将以下的配置加入到根结点下:

<Manager className="org.apache.catalina.session.PersistentManager"
      maxActiveSessions="-1"
      minIdleSwap="-1"
      maxIdleSwap="-1"
      maxIdleBackup="-1">

      <Store className="org.apache.catalina.session.JDBCStore"
        driverName="com.mysql.jdbc.Driver"
        connectionURL="jdbc:mysql://2.2.2.76:3306/test_session?user=user&password=password"
        sessionTable="sessions"
        sessionIdCol="session_id" sessionDataCol="session_data"
        sessionValidCol="valid_session" sessionMaxInactiveCol="max_inactive"
        sessionLastAccessedCol="last_access" sessionAppCol="app_name" checkInterval="60" />
</Manager>

将mysql-connector-java-5.1.34-bin.jar复制到tomcat的lib目录下。
在数据库test_session中执行以下脚本,创建用于存储session数据的表

CREATE TABLE 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)
);

使用redis保存session
如下图,多实例下可以使用redis实现分布式session管理,客户端请求,经过负载均衡分发至tomcat实例,再经过session管理,实现session在redis中存取。配置redis主从集群,主redis数据热备份至从redis,当主redis宕机了,系统自动切换至从redis,从而保证系统缓存方面高可用。

第一种方法:
在已有项目基础上加入spring Session框架来实现Session统一存储在Redis中。这种做法,不需要依赖具体的容器。参考
1.添加redis和spring session的相关依赖包。

<!-- Jedis -->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
</dependency>
<!-- Spring Data Redis -->
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-redis</artifactId>
    <version>1.7.3.RELEASE</version>
</dependency>
<!-- Spring Session -->
<dependency>
    <groupId>org.springframework.session</groupId>
    <artifactId>spring-session</artifactId>
    <version>1.2.2.RELEASE</version>
</dependency>
<!-- Apache Commons Pool -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
    <version>2.4.2</version>
</dependency>

2.在web.xml中加入以下过滤器,注意如果web.xml中有其他过滤器,一般情况下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>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>ERROR</dispatcher>
</filter-mapping>

3.在Spring配置文件中。

<bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"/>
<bean class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
    <property name="hostName" value="localhost" />
    <property name="password" value="your-password" />
    <property name="port" value="6379" />
    <property name="database" value="10" />
</bean>

4.使用。

@ResponseBody
@RequestMapping("/get")
public String index(Model model,HttpServletRequest request,String action,String msg,String key){  
    HttpSession session=request.getSession();
    String message = "ok";
    if ("set".equals(action)){
        session.setAttribute(key, msg);
    }else if ("get".equals(action)){
        message=(String)session.getAttribute(key);
    }
    return message;
}

第二种方法:
也可以像之前的MySQL一样通过容器的配置实现,参考
1.添加jedis-2.0.0.jar、tomcat-redis-session-manager-1.2-tomcat-7-java-7、commons-pool-1.3.jar 三个jar到tomcat的lib目录下;
2.修改tomcat的conf/context.xml 文件;

<Valve className="com.radiadesign.catalina.session.RedisSessionHandlerValve" />
<Manager className="com.radiadesign.catalina.session.RedisSessionManager"
             host="192.168.137.122" 
             port="6379" 
             database="0" 
             maxInactiveInterval="60"  />

3.编写Servlet处理session

protected void doGet(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {
    HttpSession session = request.getSession();
    Object userName = session.getAttribute("userName");
    if(userName == null) {
        System.out.println("user is null");
        session.setAttribute("userName", "test");
    } else {
        System.out.println("user is not null,value is " + userName);
        session.invalidate(); //调用此方法,session会在redis中删除
    }
}

5.建立多个tomcat节点,测试session是否已共享


参考:
http://2277259257.iteye.com/blog/2305870
http://www.onmpw.com/tm/xwzj/network_145.html

相关文章

网友评论

      本文标题:集群共享Session

      本文链接:https://www.haomeiwen.com/subject/sqfgmttx.html