SpringCloud 网关配置websocket

一、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连接
  }
},

  • 16
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值