插件窝 干货文章 Nginx与Tomcat怎么实现动静态分离和负载均衡

Nginx与Tomcat怎么实现动静态分离和负载均衡

server proxy 静态 Tomcat 741    来源:    2025-04-23

Nginx与Tomcat实现动静态分离与负载均衡方案

一、动静态分离实现

动静态分离是指将静态资源(HTML、CSS、JS、图片等)和动态请求(Java Servlet/JSP)分开处理,提高服务器性能。

配置步骤

  1. Nginx处理静态资源

    server {
       listen 80;
       server_name yourdomain.com;
    
       # 静态资源路径
       location ~ .*\.(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css|woff|ttf|woff2)$ {
           root /path/to/static/files;
           expires 30d;  # 设置缓存时间
       }
    
       # 动态请求转发到Tomcat
       location / {
           proxy_pass http://tomcat_server;
           proxy_set_header Host $host;
           proxy_set_header X-Real-IP $remote_addr;
           proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
       }
    }
    
  2. Tomcat配置优化

    • 在Tomcat的conf/server.xml中,确保静态资源不被处理: xml <Context docBase="/path/to/static/files" path="/static" />
    • 或者完全移除对静态资源的处理

二、负载均衡实现

1. 基础负载均衡配置

upstream tomcat_server {
    # 配置权重和健康检查
    server 192.168.1.101:8080 weight=1 max_fails=2 fail_timeout=30s;
    server 192.168.1.102:8080 weight=1 max_fails=2 fail_timeout=30s;
    server 192.168.1.103:8080 weight=2 max_fails=2 fail_timeout=30s;

    # 负载均衡策略
    # least_conn;  # 最少连接
    # ip_hash;    # IP哈希
}

server {
    listen 80;
    server_name yourdomain.com;

    location / {
        proxy_pass http://tomcat_server;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

2. 高级负载均衡策略

会话保持方案

  1. IP哈希策略

    upstream tomcat_server {
       ip_hash;
       server 192.168.1.101:8080;
       server 192.168.1.102:8080;
    }
    
  2. 使用Redis共享Session

    • 在Tomcat中配置context.xmlxml <Valve className="com.orangefunction.tomcat.redissessions.RedisSessionHandlerValve" /> <Manager className="com.orangefunction.tomcat.redissessions.RedisSessionManager" host="redis.server" port="6379" database="0" maxInactiveInterval="60" />

健康检查增强

upstream tomcat_server {
    server 192.168.1.101:8080;
    server 192.168.1.102:8080;

    # 自定义健康检查
    check interval=3000 rise=2 fall=5 timeout=1000 type=http;
    check_http_send "HEAD /health HTTP/1.0\r\n\r\n";
    check_http_expect_alive http_2xx http_3xx;
}

三、完整配置示例

# 全局配置
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    # 基础设置
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    # 日志格式
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';

    access_log /var/log/nginx/access.log main;

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;

    # Gzip压缩
    gzip on;
    gzip_types text/plain text/css application/json application/javascript text/xml;

    # 上游Tomcat服务器组
    upstream tomcat_cluster {
        least_conn;
        server tomcat1:8080 weight=1 max_fails=3 fail_timeout=30s;
        server tomcat2:8080 weight=1 max_fails=3 fail_timeout=30s;
        server tomcat3:8080 weight=2 max_fails=3 fail_timeout=30s;
    }

    # 静态资源缓存设置
    proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=static_cache:10m inactive=60m use_temp_path=off;

    server {
        listen 80;
        server_name example.com;

        # 静态资源处理
        location ~* \.(js|css|png|jpg|jpeg|gif|ico|woff2)$ {
            root /var/www/static;
            expires 365d;
            add_header Cache-Control "public";

            # 启用缓存
            proxy_cache static_cache;
            proxy_cache_valid 200 302 60m;
            proxy_cache_valid 404 1m;
        }

        # 动态请求处理
        location / {
            proxy_pass http://tomcat_cluster;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;

            # 连接超时设置
            proxy_connect_timeout 5s;
            proxy_send_timeout 10s;
            proxy_read_timeout 10s;

            # 错误处理
            proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
        }

        # 健康检查端点
        location /nginx_status {
            stub_status on;
            access_log off;
            allow 127.0.0.1;
            deny all;
        }
    }
}

四、优化建议

  1. 静态资源优化

    • 启用Gzip压缩
    • 设置合理的缓存头
    • 考虑使用CDN分发静态资源
  2. 负载均衡优化

    • 根据业务特点选择合适的负载均衡算法
    • 设置合理的超时时间
    • 实现会话保持或共享
  3. 监控与维护

    • 配置Nginx状态监控
    • 设置日志轮转
    • 定期检查服务器健康状态
  4. 安全考虑

    • 限制直接访问Tomcat端口
    • 配置适当的防火墙规则
    • 考虑启用HTTPS

通过以上配置,您可以实现Nginx与Tomcat的动静态分离和负载均衡,提高系统性能和可用性。