Nginx 负载均衡 WebSocket 请求

Nginx WebSocket 负载均衡 About 1,789 words

说明

Nginx默认方向代理超时时间为60秒,所以如果60秒内,WebSocket没有交互,则断开连接。Nginx60秒超时可使用proxy_read_timeout延长超时时间。

相关配置

Nginx 配置

proxy_read_timeout 5m:设置超时时间为5分钟。

ip_hash:保证握手阶段的HTTP请求和升级后的TCP链接在同一台机器,使得可以关联HttpSession

需要将IP信息通过proxy_set_header透传。

http {

    map $http_upgrade $connection_upgrade {
        default upgrade;
        ''      close;
    }

    upstream backend {
        ip_hash;
        server 127.0.0.1:10000;
        server 127.0.0.1:20000;
    }

    server {
        listen 8080;

        location / {
            proxy_connect_timeout 2s;
            proxy_pass http://backend;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $connection_upgrade;
            proxy_read_timeout 5m;
            proxy_set_header    Host             $host; # 保留代理之前的 host
            proxy_set_header    X-Real-IP        $remote_addr; # 保留代理之前的真实客户端 IP
            proxy_set_header    X-Forwarded-For  $proxy_add_x_forwarded_for;
            proxy_set_header    HTTP_X_FORWARDED_FOR $remote_addr; # 在多级代理的情况下,记录每次代理之前的客户端真实 IP
            proxy_redirect      default; # 指定修改被代理服务器返回的响应头中的 location 头域跟 refresh 头域数值
        }
    }

}

Java 代码

session.setMaxIdleTimeout(TimeUnit.MINUTES.toMillis(5)):设置超时时间为5分钟。

@ServerEndpoint(value = "/test/ws/{username}")
public class WebSocketServer {

    @OnOpen
    public void onOpen(@PathParam("username") String username, Session session) {
        // 最大超时时间 60 秒
        session.setMaxIdleTimeout(TimeUnit.MINUTES.toMillis(5));
        session.setMaxBinaryMessageBufferSize(8192 * 1024); // 8KB
        session.setMaxTextMessageBufferSize(8192 * 1024); // 字符数
        session.getAsyncRemote().sendText("123");
    }

    // ... 省略部分代码
}

参考

https://nginx.org/en/docs/http/websocket.html

Views: 2,776 · Posted: 2021-04-22

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh