Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> 關於Linux

Nginx + Tomcat 叢集負載均衡設定筆記(Windows 版)

Nginx 官網:https://nginx.org/,本文使用 1.5.1 版。下載解壓後,修改 conf 目錄下的 nginx.conf。

nginx.conf 主要內容

worker_processes 1;

events {
    worker_connections 1024;
}

http {
    include      mime.types;
    default_type  application/octet-stream;
    client_header_timeout  3m;
    client_body_timeout   3m;
    send_timeout       3m;
    client_header_buffer_size  1k;
    large_client_header_buffers  4 4k;
    sendfile     on;
    tcp_nopush   on;
    tcp_nodelay  on;
    keepalive_timeout  65;

    upstream localhost {
        # 依 IP 雜湊分配,很多人以為這樣能解決 session 問題,其實不能:同一台機器在多網卡環境下路由切換,IP 可能變動
        #ip_hash;
        server localhost:9097 weight=1;
        server localhost:9098 weight=1;
        server localhost:9097 backup;
        server localhost:9098 backup;
        #jvm_route $cookie_JSESSIONID|sessionid reverse;
        ip_hash;
    }

    upstream backend {
        server localhost:9097;
        server localhost:9098;
    }

    server {
        listen    9096;
        server_name  localhost;

        location ~ ^/(WEB-INF)/ {
            deny all;  # 禁止存取 WEB-INF
        }

        ### 所有靜態檔案(gif、jpg 等)由本機直接回應,根目錄為 html,快取 30 天
        location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|css|js|htm|html)$ {
            root html;
            access_log off;
            expires 30d;
        }

        location / {
            root  html;
            index  index.jsp;
            proxy_pass  https://localhost;
            proxy_redirect  off;
            proxy_set_header  Host $host;
            proxy_set_header  X-Real-IP $remote_addr;
            proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
            client_max_body_size  10m;
            client_body_buffer_size  128k;
            proxy_connect_timeout  3;
            proxy_send_timeout  3;
            proxy_read_timeout  3;
            proxy_buffer_size  4k;
            proxy_buffers  4 32k;
            proxy_busy_buffers_size  64k;
            proxy_temp_file_write_size  64k;
        }

        error_page  500 502 503 504  /50x.html;
        location = /50x.html {
            root  html;
        }
    }
}

Tomcat 端

下載 Tomcat 後,把其中一台的連接埠改為 9097,另一台改為 9098,分別啟動兩台 Tomcat 與 Nginx。在瀏覽器輸入 https://localhost:9096/ 就能看到 Tomcat 歡迎頁,重新整理幾次可觀察請求是否被分散到不同節點。

幾個實務提醒

ip_hash 只能讓同一來源 IP 盡量落到同一台,並不等於 session 共享;真正的解法是 Tomcat 的 session 複製、粘性會話(jvm_route 搭配 JSESSIONID),或把 session 外移到 Redis 這類儲存。上例中同時寫了 weight、backup 與 ip_hash,正式環境建議簡化,避免行為不如預期。

Linux 下的設定與 Windows 幾乎一致,差別在 Tomcat 需要另外設定 JAVA_HOME 等環境變數。

Copyright © Linux教程網 All Rights Reserved