【 Nginx+Apache-Tomcat7+Memcached搭建负载均衡实现Session共享】

所需环境:
Red Hat 4.4.7
JDK:Java(TM) SE Runtime Environment 1.7.0_51(开发工具包)
Nginx:nginx1.11.3(负载均衡服务器)
Apache:apache-tomcat-7.0.57(web网络服务器)
Memcached:memcached-1.4.31(分布式内存对象缓存系统)、
tomcat和memcached 集群用的jar msm-1.7  目前版本1.7 :
asm-3.2.jar
kryo-1.04.jar
kryo-serializers-0.11.jar
memcached-session-manager-1.7.0.jar
memcached-session-manager-tc7-1.8.1.jar
minlog-1.2.jar
msm-kryo-serializer-1.7.0.jar
reflectasm-1.01.jar
spymemcached-2.7.3.jar 这个将来放入各个tomcat\lib中


Libevent:libevent-2.0.22-stable(事件驱动网络库) 、 libevent-devel 1.4.13(依赖包) (安装Memcached需要依赖Libevent)
工具包:
jdk-7u51-linux-x64.rpm
nginx-1.11.3.tar.gz
apache-tomcat-7.0.57.zip
memcached-1.4.31.tar.gz
libevent-2.0.22-stable.tar.gz


所需工具包地址:http://download.csdn.net/detail/qierkang/9659233




PS:jdk、nginx、apache-tomcat、memcached、libevent都装在主机master上面,备机不需要装memcached、libevent


安装jdk-7u51-linux-x64.rpm
# rpm -ivh jdk-7u51-linux-x64.rpm
# java -version


安装apache-tomcat-7.0.57.zip
# unzip apache-tomcat-7.0.57.zip
# cd apache-tomcat-7.0.57
# chmod -R 777 *


安装nginx-1.11.3.tar.gz
# mkdir /usr/local/nginx
# tar -zxvf nginx-1.11.3.tar.gz
# cd nginx-1.11.3
# ./configure --prefix=/usr/local/nginx
# make & make install

安装报错:
./configure: error: the HTTP rewrite module requires the PCRE library.
You can either disable the module by using --without-http_rewrite_module
option, or install the PCRE library into the system, or build the PCRE library
statically from the source with nginx by using --with-pcre=<path> option.

需要安装依赖 
yum install -y pcre-devel 


./configure: error: the HTTP gzip module requires the zlib library.
You can either disable the module by using --without-http_gzip_module
option, or install the zlib library into the system, or build the zlib library
statically from the source with nginx by using --with-zlib=<path> option.

需要安装依赖
yum install -y zlib-devel


安装libevent-devel 1.4.13 (直接使用Yum安装命令就可以)
# yum install -y libevent-devel



安装libevent-2.0.22-stable.tar.gz
# tar -zxvf libevent-2.0.22-stable.tar.gz
# cd libevent-2.0.22-stable
# ./configure --prefix=/usr
# make & make install
测试:ls -al /usr/lib | grep libevent
看到服务说明安装完成




安装memcached-1.4.31.tar.gz
# tar -zxvf memcached-1.4.31.tar.gz
# cd memcached-1.4.31
# ./configure && make && make test && sudo make install
# cd /usr/local/bin/
# /usr/local/bin/memcached -d -m 1024 -u root -l 192.168.174.128 -p 11211即可启动memcached服务
测试:使用另外一台机
# telnet 192.168.174.128 11211
Trying 192.168.174.128...
Connected to 192.168.174.128.
Escape character is '^]'.
# stats
STAT pid 49505
STAT uptime 360
STAT time 1476076047
....说明安装完成 
quit








配置说明:

Nginx
例如有三台服务器:192.168.174.128(master)、192.168.174.129(slave01)、192.168.174.130(slave02)
128是主机129、130是备机


进入128 
# cd /usr/local/nginx/conf
# vi nginx.conf
内容修改如下
user root; #运行用户
worker_processes 1; #启动进程,通常设置和cpu核数一致
events{
worker_connections 1024; #单个后台worker process进程的最大并发链接数
}


#设定http服务器,利用它的反向代理功能提供负载均衡支持
http{
client_header_buffer_size 16k;#设置读取客户端请求头的缓冲区大小。多数请求缓冲1K字节是不够的。
large_client_header_buffers 4 64k;#设置用于读取大客户端请求头的缓冲区的最大数量和大小。一个请求线不能超过一个缓冲区的大小,或414(请求URI太大)错误返回到客户端。

#upstream的负载均衡
#weight为weight越大,负载的权重就越大。
#max_fails:允许请求失败的次数默认为1.当超过最大次数时

#fail_timeout:max_fails次失败后,暂停的时间。

#这边端口不一定是8080 可以是其他 如:8088-8081-8082  到时候访问地址就是

upstream localhost#定义负载均衡设备的Ip及设备状态 {
server 192.168.174.129:8080 weight=3 max_fails=2 fail_timeout=30s; 
server 192.168.174.130:8080 weight=2 max_fails=2 fail_timeout=30s;
server 127.0.0.1:8080 weight=4;
}
#配置虚拟机
server {
listen 80;#监听端口 可以是其他端口 81 82 83 88 ...
server_name localhost;#配置访问域名 域名可以有多个,用空格隔开
location  /  {# 对所有地址进行负载均衡、对以“jsp或html”结尾的地址进行负载均衡:  ~* \.(jsp|html)$
root html;
index index.html index.htm;
proxy_pass         http://localhost; #请求转向mysvr 定义的服务器列表
proxy_set_header   Host             $host;
proxy_set_header   X-Real-IP        $remote_addr;
proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
}
}
}
保存启动nginx服务
校验下nginx是否通过
# cd ../sbin
# ./nginx -t -c /usr/local/nginx/conf/nginx.config
如果出现:
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
校验成功启动服务:
# ./nginx -c /usr/local/nginx/conf/nginx.config


进入129
只需要修改nginx.conf 配置文件里面的
server {
 server_name 192.168.174.128;#主机master ip地址或者域名
 location / {
            root   /home/qek/apache-tomcat-7.0.57/webapps; #项目位置
            index  index.html index.htm index.jsp;
        }
}
保存重启nginx服务
# cd ../sbin
# ./nginx -s reload
进入130 同上




Apache-Tomcat:

# cd /home/qek/apache-tomcat-7.0.57/conf

#修改配置文件context.xml

# vi context.xml

<Context>
<!-- Default set of monitored resources -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>

    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->

    <!-- Uncomment this to enable Comet connection tacking (provides events
         on session expiration as well as webapp lifecycle) -->
    <!--
    <Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
    -->
<Manager className="de.javakaffee.web.msm.MemcachedBackupSessionManager"
   memcachedNodes="n1:192.168.174.128:11211"
   sticky="false"
   lockingMode="auto"
   sessionBackupAsync="false"
   requestUriIgnorePattern=".*\.(ico|png|gif|jpg|css|js)$"
   sessionBackupTimeout="1800000"  transcoderFactoryClass="de.javakaffee.web.msm.serializer.kryo.KryoTranscoderFactory"
/>

</Context>

#修改配置文件server.xml
#vi server.xml

 <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">
        <!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->
        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html
             Note: The pattern used is equivalent to using pattern="common" -->
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log." suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b" />

<!-- 修改tomcat 默认路访问项目路径-->
         <Context path="/" docBase="/usr/local/tomcat/apache-tomcat-7.0.57/webapps/" debug="0" reloadable="true" crossContext="true"/>
       </Host>



然后需要tomcat和memcached 集群用的jar  一共有7个分别放在msm-1.7  目前版本1.7 :
asm-3.2.jar
kryo-1.04.jar
kryo-serializers-0.11.jar
memcached-session-manager-1.7.0.jar
memcached-session-manager-tc7-1.8.1.jar
minlog-1.2.jar
msm-kryo-serializer-1.7.0.jar
reflectasm-1.01.jar
spymemcached-2.7.3.jar


PS:主机128、备机129、130配置如同


启动顺序 tomcat – nginx – memcached


测试页面index.jsp,放入webapps:
<%@ page contentType="text/html; charset=UTF-8" %> 
<%@ page import="java.util.*" %> 
<html><head><title>Cluster Test</title></head> 
<body> 
<% 
  //HttpSession session = request.getSession(true); 
  System.out.println(session.getId()); 
  out.println("<br> SESSION ID:" + session.getId()+"<br>");   
  // 如果有新的请求,则添加session属性 
  String name = request.getParameter("name"); 
  if (name != null && name.length() > 0) { 
     String value = request.getParameter("value"); 
     session.setAttribute(name, value); 
  }   
    out.print("<b>Session List:</b>");   
    Enumeration<String> names = session.getAttributeNames(); 
    while (names.hasMoreElements()) { 
        String sname = names.nextElement();  
        String value = session.getAttribute(sname).toString(); 
        out.println( sname + " = " + value+"<br>"); 
        System.out.println( sname + " = " + value); 
   } 
%> 
</body> 
</html>

结果:session Id返回一样 例如:B860FA4DBB36B8B9CE75CAAF11A3AD6C-n1




ps:如果java程序有用到session 把获取session用spymemcached管理 修改如下:

获取session方式有变化:

maven最大的配置文件 在里面加入pom.xml

  <dependency>
   <groupId>net.spy</groupId>
   <artifactId>spymemcached</artifactId>
   <version>2.12.1</version>
</dependency>


java代码:

package com.sfc.utils;


import java.net.InetSocketAddress;
import java.util.concurrent.Future;
import net.spy.memcached.MemcachedClient;


/**
    * @ClassName: MemcachedSession
    * @author qierkang
    * @date 2016年10月20日
* @Description: (  )
    */    
public class MemcachedSession{


   /**
   * @Fields serialVersionUID : (  )
   */ 
private final static String MEMCACHED_IP="你的master服务器"; //主服务器master IP地址
private final static Integer MEMCACHED_PORT=11211;//memcached 开放端口

   /**
   * @Title: setMemcachedSession
   * @param @param request
   * @param @return    参数
   * @return boolean    返回类型
   * @Description: ( 往memcached添加sessionID )
   */
public static boolean setMemcachedSession(String sessionId){
Future<Boolean> b = null;
boolean flag=false;
try{
/*建立MemcachedClient 实例,并指定memcached服务的IP地址和端口号*/  
MemcachedClient mc = new MemcachedClient(new InetSocketAddress(MEMCACHED_IP, MEMCACHED_PORT));
            /*将key值,过期时间(秒)和要缓存的对象set到memcached中*/  
            b = mc.set("qekKey", 3600, sessionId);
            flag=b.get();
            if(b.get().booleanValue()==true){
                mc.shutdown();  
            } 
        }
        catch(Exception ex){
            ex.printStackTrace();  
        }
return flag;
}

   /**
   * @Title: getMemcachedSession
   * @param @return    参数
   * @return String    返回类型
   * @Description: ( 从memcached获取sessionID )
   */
public static String getMemcachedSession(){
String key=null;
try{
            /*建立MemcachedClient 实例,并指定memcached服务的IP地址和端口号*/  
MemcachedClient mc = new MemcachedClient(new InetSocketAddress(MEMCACHED_IP, MEMCACHED_PORT));
            /*按照key值从memcached中查找缓存,不存在则返回null */  
key=mc.get("qekKey").toString();  
            mc.shutdown();  
        }  
        catch(Exception ex){  
            ex.printStackTrace();  
        }
return key;
}

}

本人亲自测试可以用!

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页