问题:websocket连接后,重启后台服务,websocket未重连或者在重连时后台服务还未重启好,导致需要刷新浏览器才能重新连接websocket。
一、定义连接状态
isConnected: false // 默认未连接
二、websocket连接
initStompClient() {
// 如果已经连接,直接返回,不进行新的连接尝试
if (this.isConnected) {
return
}
console.log('进入websocket连接....')
this.stompClient = Stomp.over(
new SockJS(`/web_socket/websocket?token=${sessionStorage.getItem('token')}`)
)
// this.stompClient.debug = () => {}
this.stompClient.connect(
{
id: new Date().getTime(),
'client-id': 'data-visualization'
},
(frame) => {
console.log('进入connectCallback....', frame)
this.$store.dispatch('stompClientAction', this.stompClient)
this.isConnected = true // 连接成功,设置连接状态为true
},
(err) => {
console.log('进入errorCallback....', err)
}
)
},
三、添加重连机制
initStompClient() {
// 如果已经连接,直接返回,不进行新的连接尝试
if (this.isConnected) {
return
}
console.log('进入websocket连接....')
this.stompClient = Stomp.over(
new SockJS(`/web_socket/websocket?token=${sessionStorage.getItem('token')}`)
)
// this.stompClient.debug = () => {}
this.stompClient.connect(
{
id: new Date().getTime(),
'client-id': 'data-visualization'
},
(frame) => {
console.log('进入connectCallback....', frame)
this.$store.dispatch('stompClientAction', this.stompClient)
this.isConnected = true // 连接成功,设置连接状态为true
},
(err) => {
console.log('进入errorCallback....', err)
console.log('断开连接,5秒后进入重连....')
this.$store.dispatch('stompClientAction', null)
if (this.stompClientTimer) {
clearInterval(this.stompClientTimer)
}
this.isConnected = false
this.stompClientTimer = setInterval(() => {
this.initStompClient()
}, 5000)
}
)
},
四、优化
在后台服务未重启好之前保持5s重连一次,但是限制最多重连10次,一般正常情况下,10次之内后台服务应该已经重启完了。
reconnectCount: 0, // 重连次数,最多10次
initStompClient() {
// 如果已经连接,直接返回,不进行新的连接尝试
if (this.isConnected) {
return
}
console.log('进入websocket连接....')
this.stompClient = Stomp.over(
new SockJS(`/web_socket/websocket?token=${sessionStorage.getItem('token')}`)
)
// this.stompClient.debug = () => {}
this.stompClient.connect(
{
id: new Date().getTime(),
'client-id': 'data-visualization'
},
(frame) => {
console.log('进入connectCallback....', frame)
this.$store.dispatch('stompClientAction', this.stompClient)
this.isConnected = true // 连接成功,设置连接状态为true
this.reconnectCount = 0 // 连接成功后重置重连次数为0
},
(err) => {
console.log('进入errorCallback....', err)
// this.stompClient.disconnect(() => {
console.log('断开连接,5秒后进入重连....')
this.$store.dispatch('stompClientAction', null)
if (this.stompClientTimer) {
clearInterval(this.stompClientTimer)
}
this.isConnected = false
this.reconnectCount += 1 // 重连次数加1
// 判断重连次数是否达到10次,如果达到则停止重连并给出提示
console.log(`第${this.reconnectCount}次重连......`)
if (this.reconnectCount > 10) {
console.log('已达到最大重连次数,停止重连,请检查网络或联系管理员或刷新页面')
return
}
this.stompClientTimer = setInterval(() => {
this.initStompClient()
}, 5000)
// })
}
)
},