如何通过队列扩展websocket客户端

问题描述

我正在使用提供酒店信息的第三方API;它提供的选项之一是在有人进行预订时发出Websocket通知,因此,通过创建客户端并接收广播消息,我知道何时进入API的端点并获取有关预订的所有信息。现在,我只想将消息写到队列中。我使用“ ws”库编写了一个简单的node.js Web应用程序,该应用程序接收websocket消息并将其写入Azure存储队列:

// Import the libraries I need for websockets,Azure storage queues and some config files
const env = require('dotenv').config();
const WebSocket = require('ws');
const config = require('./config');
const { QueueClient } = require('@azure/storage-queue');

var queueName,createQueueResponse,fullUrl,sendMessageResponse;

let connectionString = process.env.AZURE_STORAGE_CONNECTION_STRING;

// Get wss://clientsite URL and query string parameters from a config file
const { url: { site,myToken,hotelToken } } = config;

// Create a name for the queue. 
queueName = process.env.HOTEL_ID;

// Instantiate a QueueClient which will be used to create and manipulate a queue
var queueClient = new QueueClient(connectionString,queueName);

// Create the queue
(async () => {
     createQueueResponse = await queueClient.createIfNotExists();
     if (createQueueResponse.requestId) {
         console.log("Queue created,requestId =",createQueueResponse.requestId);
     }
     else {
         console.log("Queue not created");
     }
 })();

//Create the websocket
 fullUrl = `${site}?ClientToken=${myToken}&Accesstoken=${hotelToken}`;
 var ws = new WebSocket(fullUrl);

//Write the received messages to the queue   
ws.on('message',async function incoming(data) {
     if (data) {
         sendMessageResponse = await queueClient.sendMessage(data);
         console.log("Messages added,requestId:",sendMessageResponse.requestId);
     }
});

ws.on('error',function error(error) {
     console.log("Error: " + error.message);
});

但是我希望能够侦听来自数百个websocket的消息,并跟踪哪个来源,也许是通过将每个websocket链接到不同的队列。但是,当我尝试遍历WebSocket URL列表并为每个URL创建一个队列来进行尝试时,它们最终都使用我创建的最终队列。

将websocket客户端可伸缩地绑定到队列的正确方法是什么?我已经研究过使用SignalR,但是所有示例都是关于如何创建聊天室的!

解决方法

Azure Web Apps已为每个SKU设置了服务限制,其中包括websocket数量和内存的上限。您可以看到它们here。即使标准层SKU具有无限的Web套接字,您在某些时候也会遇到内存限制。您可以通过预配置多个Web App实例(标准层最多10个)来进一步扩展。

在解决了大约四年的问题之后,我们扩展了自托管网络套接字,并使用了SignalR服务。您可以使用SignalR服务将成千上万的已连接客户端运行。我强烈建议您使用它来避免头痛。