用习惯了HaProxy,最近用到关于WebSocket的负载上也涉及到这块,做个记录。

单纯使用ha的tcp或者http负载,会出现链接断开的情况,此处需重点关注Connection: Upgrade头,会让client端知道server端会改变协议,变成如Upgrade: websocketheader中所述的协议。若服务端提供,则会返回:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: tD0l5WXr+s0lqKRayF9ABifcpzY=
Sec-WebSocket-Protocol: echo-protocol

下图为整体的交互图:

HaProxy对websocket的负载

具体配置

#**** WSS ****# 
frontend WSS_SSL
    bind *:443 ssl crt /etc/ssl/name.pem 
    mode http
    
    ## routing based on websocket protocol header
    acl hdr_connection_upgrade hdr(Connection)  -i upgrade
    acl hdr_upgrade_websocket  hdr(Upgrade)     -i websocket
    use_backend wss_srv if hdr_connection_upgrade hdr_upgrade_websocket
 
backend wss_srv
    balance roundrobin
    cookie SERVERID
    server host1 192.168.1.10:80  cookie host1 maxconn 50000 check inter 10s rise 3 fall 3  

WS同理。