nginx+tomcat+memcached負載均衡集群搭建詳細筆記(上)

jopen 9年前發布 | 83K 次閱讀 Nginx Web服務器

    忙了三天,終于把nginx+tomcat+memcached負載均衡集群搭建成功,真的非常興奮,在此和大家一起分享一下我的成果,希望對大家今后的學習有所幫助,哈哈!首先我強調的是我用的操作系統是CentOS6.4,而且開的是一個VMWARE,其實也沒什么影響,但是在Ubuntu下搭建的話,就可能有些許不一樣,在centos下我們需要手動去下載一些額外的資源文件。好了,說了這么多,咱們開始吧

    前言:本文檔主要講解,如何在CentOS6.4下搭建Nginx+Tomcat+Memcached負載均衡集群服務器。

                (1)Nginx負責負載均衡。

                (2)Tomcat負責實際服務。

                (3)Memcached負責同步Tomcat的Session,達到Session共享的目的。

     1、首先我們來安裝一下JDK吧,這不是必須要放在第一步,只是我自己之前在學習hadoop時就已經安裝了JDK。

          我使用的JDK版本:jdk-6u24-linux-i586.bin(下載地址:JDK下載

         1.1將下載好的JDK放進 local/usr/文件路徑下(我所有下載的.tar.gz和.bin文件都是放在該路徑下的,以便于以后查找),如果你用的是VMWARE,你可以使用WinSCP來將要傳送的文件復制到該路徑下即可。

         1.2然后使用linux命令解壓

tar -zvxf jdk-6u24-linux-i586.bin


          1.3安裝完成之后,我將其重命名為jdk,只是這樣看著比較舒服

    mv jdk-6u24-linux-i586 jdk


         1.4接著我們編輯/etc/profile,輸入linux命令

gedit /etc/profile


         1.5編輯profile文件,添加以下文本

export JAVA_HOME=/usr/local/jdk  
   export PATH=$PATH:$JAVA_HOME/bin


         1.6驗證jdk是否安裝成功

java -version



      2、安裝nginx


         Nginx官網:http://nginx.org/ 

        在安裝Nginx之前,需要先安裝gcc、 openssl、 pcre和zlib軟件庫,這些貌似在Ubuntu下有些就不需要安裝的,根據你自己的需要進行安裝。

        首先我們來談一下如果缺少這些問題會報哪些錯誤以及解決方案:

        1)缺少pcre library
             ./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. 

        當執行./configure的時候會拋出說缺少PCRE library 這個是HTTP Rewrite 模塊,也即是url靜態化的包


所以首先我們要安裝這個東西  PCRE下載PCRE ,我選擇的是pcre-8.36.tar.gz版本

# tar zxvf pcre-8.36.tar.gz

./configure

make

make install </pre>


</p>

        2)缺少gcc-c++,也就是c++編譯包 

             libtool: compile: unrecognized option `-DHAVE_CONFIG_H' 
libtool: compile: Try `libtool --help' for more information. 
make[1]: *** [pcrecpp.lo] Error 1 
make[1]: Leaving directory `/usr/local/src//pcre-8.31' 
make: *** [all] Error 2root@wolfdog-virtual-machine:~/work/pcre-8.12$ libtool -help -DHAVE_CONFIG_H 
The program 'libtool' is currently not installed. You can install it by typing: 
sudo apt-get install libtool 

  在線安裝:輸入命令:

yum install libtool 


                   再輸入

yum install gcc-c++ 


        3)缺少openssl庫

          ./configure: error: the HTTP cache module requires md5 functions 
from OpenSSL library. You can either disable the module by using 
--without-http-cache option, or install the OpenSSL library into the system, 
or build the OpenSSL library statically from the source with nginx by using 
--with-http_ssl_module --with-openssl=<path> options. 

          openssl官網:openssl下載

          在線安裝: 

yum install openssl libssl-dev libperl-dev


        4)缺少zlib庫

          ./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. 

       zlib官網:下載zlib

       在線安裝:


yum install zlib
yum install zlib-devel


         2.1接著安裝nginx,版本為:nginx-1.7.9.tar.gz

# ./configure

# make  
# sudo make install</pre> <p><br />

</p>

       1)解壓

 tar -zxvf nginx-1.7.9.tar.gz
          cd nginx-1.7.9


2)安裝

# ./configure

make

make install </pre></div>

         2.2安裝完之后我們就可以在nginx的conf文件夾下面創建一個proxy.conf文件,配置一些代理參數

$cd /usr/local/nginx/conf
$sudo touch proxy.conf

#!nginx (-)

proxy.conf

proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; #獲取真實ip

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #獲取代理者的真實ip

client_max_body_size 10m; client_body_buffer_size 128k; proxy_connect_timeout 90; proxy_send_timeout 90; proxy_read_timeout 90; proxy_buffer_size 4k; proxy_buffers 4 32k; proxy_busy_buffers_size 64k; proxy_temp_file_write_size 64k;</pre>



        2.3接著,我們要編輯nginx.conf文件

gedit nginx.conf


         寫上基本配置:

#運行nginx所在的用戶名和用戶組

user www www;

啟動進程數

worker_processes 8;

全局錯誤日志及PID文件

error_log /usr/local/nginx/logs/nginx_error.log crit;

pid /usr/local/nginx/nginx.pid;

Specifies the value for maximum file descriptors that can be opened by this process.

worker_rlimit_nofile 65535;

工作模式及連接數上限

events
{
use epoll;
worker_connections 65535;
}

設定http服務器,利用它的反向代理功能提供負載均衡支持

http
{

設定mime類型

include mime.types;
default_type application/octet-stream;
include /usr/local/nginx/conf/proxy.conf;

charset gb2312;

設定請求緩沖

server_names_hash_bucket_size 128;
client_header_buffer_size 32k;
large_client_header_buffers 4 32k;
client_max_body_size 8m;

sendfile on;
tcp_nopush on;

keepalive_timeout 60;

tcp_nodelay on;

fastcgi_connect_timeout 300;

fastcgi_send_timeout 300;

fastcgi_read_timeout 300;

fastcgi_buffer_size 64k;

fastcgi_buffers 4 64k;

fastcgi_busy_buffers_size 128k;

fastcgi_temp_file_write_size 128k;

gzip on;

gzip_min_length 1k;

gzip_buffers 4 16k;

gzip_http_version 1.0;

gzip_comp_level 2;

gzip_types text/plain application/x-javascript text/css application/xml;

gzip_vary on;

limit_zone crawler $binary_remote_addr 10m;

禁止通過ip訪問站點

server{
servername ;
return 404;
}

server
{
listen 80;
server_name localhost;
index index.html index.htm index.jsp;#設定訪問的默認首頁地址
root /home/www/web/ROOT;#設定網站的資源存放路徑

#limit_conn   crawler  20;      

location ~ .*.jsp$ #所有jsp的頁面均交由tomcat處理  
{  
  index index.jsp;  
  proxy_pass http://localhost:8080;#轉向tomcat處理  
  }  


location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ #設定訪問靜態文件直接讀取不經過tomcat  
{  
  expires      30d;  
}  

location ~ .*\.(js|css)?$  
{  
  expires      1h;  
}      

定義訪問日志的寫入格式

 log_format  access  '$remote_addr - $remote_user [$time_local] "$request" '  
          '$status $body_bytes_sent "$http_referer" '  
          '"$http_user_agent" $http_x_forwarded_for';  
access_log  /usr/local/nginx/logs/localhost.log access;#設定訪問日志的存放路徑  

  }     

}</pre>



          2.4然后我們運行linux命令


#/usr/local/nginx/sbin/nginx -t


如果屏幕顯示以下兩行信息,說明配置文件正確:  

the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok

the configuration file /usr/local/nginx/conf/nginx.conf was tested successfull
</blockquote> </div> </div> 但是這個時候一般會出現一個問題說是

error while loading shared libraries: libpcre.so.1: cannot open shared object file: No such file or directory 
解決方法:


# ln -s /usr/local/lib/libpcre.so.1 /lib64

32位系統則:


ln -s /usr/local/lib/libpcre.so.1 /lib

注:
/usr/local/lib/libpcre.so.1 為prce安裝后的文件地址
低版本prce對應的libpcre.so.1 為libpcre.so.0


          2.5啟動與關閉Nginx

                1)啟動

#/usr/local/nginx/sbin/nginx


                  重啟:

/usr/local/nginx/sbin/nginx -s reload


      2)關閉

#/usr/local/nginx/sbin/nginx -s stop
或:
ps -ef | grep nginx
找到主進程ID,然后kill即可,如:


# kill -9 [進程號]

好了,這樣nginx就安裝好了。

(3)檢查是否啟動成功:
netstat -ano " grep80 "有結果輸入說明啟動成功
打開瀏覽器訪問此機器的 IP,如果瀏覽器出現Welcome to nginx! 則表示 Nginx 已經安裝并運行成功。如果已經配置了負載均衡服務器,則會看Tomcat中的網站頁面

           3、安裝memcached

              Memcached官網:點擊進入
</span></span></span></span>

               3.1由于memcached安裝時,需要使用libevent類庫,所以先安裝libevent 下載地址:點擊進入

                 我下載的是版本:libevent-1.4.14b-stable.tar.gz

               3.2解壓:

libevent-1.4.14b-stable.tar.gz
               3.3進入


cd libevent-1.4.14b-stable 
              3.4編譯安裝(默認安裝到/usr/local/lib/目錄)


# ./configure

make

make install </pre>             3.5安裝memcached,memcached下載網址:http://www.danga.com/memcached/download.bml


</p>

1. 解壓縮
tar xzfv memcached-1.4.22.tar.gz

  1. 進入到 memcached-1.4.22目錄
    cd memcached-1.4.22
  2. 編譯,安裝
    ./configure --prefix=/local/memcached
    make
    make install</pre>安裝完成后,會在 /local/memcached 出現 bin和share目錄



    進行 bin目錄,啟動 memcache
    方法如下: 
    ./memcached -d -u nobody -m 512 127.0.0.1 -p 11211
    此時,會報一個異常
     error while loading shared libraries: libevent-1.4.so.2: cannot open shared object file: No such file or directory

    原因是找不到libevent-1.4.so.2類庫,解決辦法如下:


    使用LD_DEBUG=help ./memcached -v來確定 加載的類庫路徑,方法如下:
    LD_DEBUG=libs ./memcached -v 2>&1 > /dev/null | less
    則系統會顯示:


    linux:/local/memcached/bin # LD_DEBUG=libs ./memcached -v 2>&1 > /dev/null | less  
      20421:     find library=libevent-1.4.so.2; searching  
      20421:      search cache=/etc/ld.so.cache  
      20421:      search path=/lib/tls/i686/sse2:/lib/tls/i686:/lib/tls/sse2:/lib/tls:/lib/i686/sse2:/lib/i686:/lib/sse2:/lib:/usr/lib/tls/i686  
    /sse2:/usr/lib/tls/i686:/usr/lib/tls/sse2:/usr/lib/tls:/usr/lib/i686/sse2:/usr/lib/i686:/usr/lib/sse2:/usr/lib          (system search path)  
      20421:       trying file=/lib/tls/i686/sse2/libevent-1.4.so.2  
      20421:       trying file=/lib/tls/i686/libevent-1.4.so.2  
      20421:       trying file=/lib/tls/sse2/libevent-1.4.so.2  
      20421:       trying file=/lib/tls/libevent-1.4.so.2  
      20421:       trying file=/lib/i686/sse2/libevent-1.4.so.2  
      20421:       trying file=/lib/i686/libevent-1.4.so.2  
      20421:       trying file=/lib/sse2/libevent-1.4.so.2  
      20421:       trying file=/lib/libevent-1.4.so.2  
      20421:       trying file=/usr/lib/tls/i686/sse2/libevent-1.4.so.2  
      20421:       trying file=/usr/lib/tls/i686/libevent-1.4.so.2  
      20421:       trying file=/usr/lib/tls/sse2/libevent-1.4.so.2  
      20421:       trying file=/usr/lib/tls/libevent-1.4.so.2  
      20421:       trying file=/usr/lib/i686/sse2/libevent-1.4.so.2  
      20421:       trying file=/usr/lib/i686/libevent-1.4.so.2  
      20421:       trying file=/usr/lib/sse2/libevent-1.4.so.2  
      20421:       trying file=/usr/lib/libevent-1.4.so.2  
      20421:      
    ./memcached: error while loading shared libraries: libevent-1.4.so.2: cannot open shared object file: No such file or directory

    我們看到,memcached會到很多地方去找,所以根據其它求,我們只需建一個軟鏈接,指定到我們安裝的類庫上即可方法如下:  
    ln -s /usr/local/lib/libevent-1.4.so.2 /lib/libevent-1.4.so.2  
    現在可以正常啟動memcached了  
    ./memcached -d -u nobody -m 512 127.0.0.1 -p 11211  
    memcache啟動參數說明:
    安裝好了就可以使用memcached了,下面我用一種最簡單的官方提供的方法java_memcached_releas



    可以到這里去下載https://github.com/gwhalin/Memcached-Java-Client/downloads

           1)工具類


    package org.memcached.dhp.test;

import java.util.Date;

import com.danga.MemCached.MemCachedClient; import com.danga.MemCached.SockIOPool;

/**

  • <pre><b>功能描述:</b>Memcached的 工具類
  • @author xie)<br>
  • <b>修改歷史:</b>(修改人,修改時間,修改原因/內容)
  • </pre> */
    public final class MemcachedUtil { /**

    • <b>構造函數:工具類,禁止實例化</b>
    • */ private MemcachedUtil() {

      } // 創建全局的唯一實例 private static MemCachedClient mcc = new MemCachedClient();

      /**

    • 自身實例 */
      private static MemcachedUtil memcachedUtil = new MemcachedUtil();

      // 設置與緩存服務器的連接池 static { // 服務器列表和其權重
      String[] servers = {"192.168.13.100:11211" };// Ip地址和端口號
      // 權重
      Integer[] weights = {3 }; // 獲取socket連接池的實例對象
      SockIOPool pool = SockIOPool.getInstance(); // 設置服務器信息 pool.setServers(servers); pool.setWeights(weights);

      // 設置初始連接數、最小和最大連接數以及最大處理時間 pool.setInitConn(5); pool.setMinConn(5); pool.setMaxConn(250); pool.setMaxIdle(1000 60 60 * 6);

      // 設置主線程的睡眠時間 pool.setMaintSleep(30); // 設置TCP的參數,連接超時等 pool.setNagle(false);
      pool.setSocketTO(3000);
      pool.setSocketConnectTO(0);

      // 初始化連接池 pool.initialize(); // 壓縮設置,超過指定大小(單位為K)的數據都會被壓縮
      // mcc.setCompressEnable(true);
      // mcc.setCompressThreshold(64 * 1024);

      mcc.setPrimitiveAsString(true); // 設置序列化 } /**

    • <pre><b>功能描述:</b>獲取唯一實例.
    • @author :xiezhaodong
    • <b>創建日期 :</b>2012-4-25 上午10:57:41
    • @return
    • <b>修改歷史:</b>(修改人,修改時間,修改原因/內容)
    • </pre> */ public static MemcachedUtil getInstance() {

      return memcachedUtil;
      } /**

    • <pre><b>功能描述:</b>新增一個緩存數據
    • @author :xiezhaodong
    • <b>創建日期 :</b>2012-4-25 上午10:55:15
    • @param key 緩存的key
    • @param value 緩存的值
    • @return 操作結果

    • <b>修改歷史:</b>(修改人,修改時間,修改原因/內容)

    • </pre> */ public boolean add(String key, Object value) { // 不會存入緩存 return mcc.add(key, value); // return mcc.set(key, value); } /**
    • <pre><b>功能描述:</b>新增一個緩存數據
    • @author :xiezhaodong
    • <b>創建日期 :</b>2012-4-25 上午10:56:15
    • @param key 緩存的key
    • @param value 緩存的值
    • @param expiry 緩存過期的時間
    • @return 操作結果
    • <b>修改歷史:</b>(修改人,修改時間,修改原因/內容)
    • </pre> */ public boolean add(String key, Object value, Date expiry) { // 不會存入緩存 return mcc.add(key, value, expiry); // return mcc.set(key, value, expiry); }

      /**

    • <pre><b>功能描述:</b>替換已有的緩存數據
    • @author :xiezhaodong
    • <b>創建日期 :</b>2012-4-25 上午10:55:34
    • @param key 設置對象的key
    • @return Object 設置對象的值
    • @return 是否替換成功
    • <b>修改歷史:</b>(修改人,修改時間,修改原因/內容)
    • </pre> */ public boolean replace(String key, Object value) { return mcc.replace(key, value); } /**
    • <pre><b>功能描述:</b>替換已有的緩存數據
    • @author :xiezhaodong
    • <b>創建日期 :</b>2012-4-25 上午10:43:17
    • @param key 設置對象的key
    • @return Object 設置對象的值
    • @param expiry 過期時間
    • @return 是否替換成功
    • <b>修改歷史:</b>(修改人,修改時間,修改原因/內容)
    • </pre> */ public boolean replace(String key, Object value, Date expiry) {

      return mcc.replace(key, value, expiry);
      } /**

    • <pre><b>功能描述:</b>根據指定的關鍵字獲取對象
    • @author :xiezhaodong
    • <b>創建日期 :</b>2012-4-25 上午10:42:49
    • @param key 獲取對象的key
    • @return Object 對象值
    • <b>修改歷史:</b>(修改人,修改時間,修改原因/內容)
    • </pre> */ public Object get(String key) { return mcc.get(key); }

}</pre>


       2)對象,必須實現序列化接口


package org.memcached.dhp.test;

import java.io.Serializable;

public class Employee implements Serializable {

/**
 * serialVersionUID
 */
private static final long serialVersionUID = -271486574863799175L;

/** 
 * 員工名字 
 */  
private String EmpName;  

/** 
 * 部門名 
 */  
private String deptName;  

/** 
 * 公司名 
 */  
private String companyName;  

/** 
 *  
 * <b>構造函數:</b> 
 *  
 */  
public Employee() {  

}

/** 
 * Access method for the empName property 
 *  
 * @return the empName 
 */  
public String getEmpName() {  

    return EmpName;  
}  

/** 
 * Sets the value of empName the property 
 *  
 * @param empName the empName to set 
 */  
public void setEmpName(String empName) {  

    EmpName = empName;  
}  

/** 
 * Access method for the deptName property 
 *  
 * @return the deptName 
 */  
public String getDeptName() {  

    return deptName;  
}  

/** 
 * Sets the value of deptName the property 
 *  
 * @param deptName the deptName to set 
 */  
public void setDeptName(String deptName) {  

    this.deptName = deptName;  
}  

/** 
 * Access method for the companyName property 
 *  
 * @return the companyName 
 */  
public String getCompanyName() {  

    return companyName;  
}  

/** 
 * Sets the value of companyName the property 
 *  
 * @param companyName the companyName to set 
 */  
public void setCompanyName(String companyName) {  

    this.companyName = companyName;  
}

}</pre>       3)測試類


package org.memcached.dhp.test;

public class MemcachedUtilTest { public static void main(String[] args) { //add();

    print();
}
private static void print() {
    MemcachedUtil cache = MemcachedUtil.getInstance();
    Employee emp=(Employee) cache.get("emp");  
    System.out.println("name:"+emp.getCompanyName());  
    System.out.println("dep:"+emp.getDeptName());  
    System.out.println("emp:"+emp.getEmpName()); 
}

private static void add() {
    MemcachedUtil cache = MemcachedUtil.getInstance();  

    Employee emp = new Employee();  
    emp.setCompanyName("Kevin's Company");  
    emp.setDeptName("R&D Dept");  
    emp.setEmpName("Kevin");  


    cache.add("emp", emp);
}

}</pre>
     小結:今天太累了,寫不動了,下一篇我將和大家分享Tomcat+memcached配置,實現session共享,敬請期待吧~

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!