一、nginx
https://域名.com
location /websocket/ {
proxy_pass http://172.1.1.173:8181/; #内网网关IP
proxy_http_version 1.1;
proxy_read_timeout 360s;
proxy_redirect off;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade"; #配置连接为升级连接
proxy_set_header Host $host:$server_port;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
二、网关
1、routes配置
- id: id-websocket
uri: lb:ws://zzf-websocket
predicates:
- Path=/ws/**
zzf-websocket 为websocket 微服务 服务名称
2、安全配置(白名单)
security:
ignore:
whites:
- /ws/**
三、web
.env.production
# Websocket VUE_APP_WS_URL = 'wss://域名.com/websocket/ws/'
vue:
setupWebSocket() { try { this.websocket = new WebSocket(process.env.VUE_APP_WS_URL + '/orderWebsocket') // 创建WebSocket连接 this.websocket.onopen = this.onWebSocketOpen // WebSocket连接打开时的处理函数 this.websocket.onmessage = this.onWebSocketMessage // 收到WebSocket消息时的处理函数 this.websocket.onclose = this.onWebSocketClose // WebSocket连接关闭时的处理函数 } catch (e) { console.error(e) } }, onWebSocketMessage(event) { const message = event.data console.log('onWebSocketMessage {}',message) this.notifyOrder(message); this.$modal.notifySuccess(message); }, onWebSocketClose() { console.log(this.reconnectCount+ ' WebSocket connection is closed') this.stopHeartbeat() // WebSocket连接关闭时,停止心跳检测 if(this.reconnectCount>0){ setTimeout(this.setupWebSocket, this.reconnectInterval) // 在一定时间后重连WebSocket this.reconnectCount --; } }, startHeartbeat() { this.heartbeatInterval = setInterval(() => { if (this.websocket && this.websocket.readyState === WebSocket.OPEN) { this.websocket.send('ping') // 发送心跳消息 } }, 10000) // 每10秒发送一次心跳 }, stopHeartbeat() { if (this.heartbeatInterval) { clearInterval(this.heartbeatInterval) // 停止心跳检测定时器 } }, onWebSocketOpen() { console.log('链接成功') }, closeWebSocket() { if (this.websocket) { this.websocket.close() // 关闭WebSocket连接 } },