WebSocket是一种新的HTML5协议,它实现了浏览器与服务器全双工通信,能更好地节省服务器资源和带宽并达到实时通讯。本文介绍如何在多活空间接入WebSocket协议集群,目前WebSocket仅支持异地多活。
步骤一:创建WebSocket协议集群
步骤二:WebSocket协议集群加入接入层集群
步骤三:创建WebSocket协议域名
验证WebSocket多活
上述URI配置的回源应用ip:port是两个单元各自的WebSocket Server的地址。在本示例中,WebSocket Server主要业务逻辑就是定时的向所有Client广播消息,表明自己所在单元。
您可以重点关注Client,以下示例采用NodeJS的WebSocket Library:
const WebSocket = require('ws');
let host = "http://websocket.msha.tech/";
let routerId = 1111;
// routerId = 6249;
routerId = 8330;
let options = {
'headers': {
routerId: routerId,
unitType: "unit_type",
}
};
let ws = handleWs();
function handleWs(){
let ws = new WebSocket(host,[],options);
ws.on('upgrade', function open(resp) {
// console.log('upgrade ',resp);
});
ws.on('open', function open() {
console.log('connected:'+routerId);
ws.send(Date.now());
});
ws.on('error', function error(e) {
console.log('err',e);
});
ws.on('close', function close() {
console.log('disconnected');
//断连后重连。
let retryTime = 1500;
setTimeout(()=>{
console.log('!!! reconnecting in ...'+retryTime+' ms');
ws = handleWs();
}, retryTime);
});
ws.on('message', function incoming(data) {
console.log(`msg: ${data} `);
});
ws.on('unexpected-response', function handleerr(req,resp) {
//处理重定向。
if ((resp.statusCode+'').startsWith("30")){
console.log("!!! redirecting... from ", host," to",resp.headers.location);
host = resp.headers.location;
ws = handleWs();
}
});
return ws;
}
单元分流
切流
在文档使用中是否遇到以下问题
更多建议
匿名提交