在 Azure 函数中管理 SignalR 服务中的组

Managing groups in SignalR service in Azure function

我已经实现了协商端点和发送方法,并从 signalR JS 客户端连接。我正在连接并能够向所有连接的客户端广播消息。根据我们的要求,我必须将消息发送给几个客户。从文档中,我相信我们可以向一个组发送消息。我已经编写了一个用于向组中添加和删除用户的 azure 函数。

 [FunctionName("AddToGroup")]
        public static Task AddToGroup(
            [HttpTrigger(AuthorizationLevel.Function, "get")] HttpRequest req,
            ILogger log,
            [SignalR(HubName = NotificationConstants.Hub)]IAsyncCollector<SignalRGroupAction> signalRGroupActions)
        {
            string userId = req.Query[NotificationConstants.QueryStringUserId];
            string companyId = req.Query[NotificationConstants.QueryStringCompanyId];
            return signalRGroupActions.AddAsync(
                 new SignalRGroupAction
                 {
                     UserId = userId,
                     GroupName = string.Format(CultureInfo.CurrentCulture,
                                NotificationConstants.Group,
                                companyId),
                     Action = GroupAction.Add
                 });
        }

    [FunctionName("RemoveFromGroup")]
    public static Task removeFromGroup(
       [HttpTrigger(AuthorizationLevel.Function, "get")] HttpRequest req,
       ILogger log,
       [SignalR(HubName = NotificationConstants.Hub)]IAsyncCollector<SignalRGroupAction> signalRGroupActions)
    {
        string userId = req.Query[NotificationConstants.QueryStringUserId];
        string companyId = req.Query[NotificationConstants.QueryStringCompanyId];
        return signalRGroupActions.AddAsync(
             new SignalRGroupAction
             {
                 UserId = userId,
                 GroupName = string.Format(CultureInfo.CurrentCulture,
                            NotificationConstants.Group,
                            companyId),
                 Action = GroupAction.Remove
             });
    }

如何从 JS 客户端调用它?我的示例客户端代码如下。请推荐

function GetConnectionInfo() {
    return axios.get('http://localhost:7071/api/ConnectionInfo?UserId=1_2347')
        .then(function (response) {
            return response.data;
        }).catch(console.error);
}

function StartConnection(connection) {
    console.log('connecting...');
    connection.start()
        .then(function () {
            console.log('connected!');
            connection.invoke('getConnectionId')
                .then(function (connectionId) {
                    console.log(connectionId);
                    // Send the connectionId to controller
                });

        })
        .catch(function (err) {
            console.error(err);
            setTimeout(function () { StartConnection(connection); }, 2000);
        });
}

GetConnectionInfo().then(function (info) {
    let accessToken = info.accessToken;
    const options = {
        accessTokenFactory: function () {
            if (accessToken) {
                const _accessToken = accessToken;
                accessToken = null;
                return _accessToken;
            } else {
                return GetConnectionInfo().then(function (info) {
                    return info.accessToken;
                });
            }

        }
    };

    const connection = new signalR.HubConnectionBuilder()
        .withUrl(info.url, options)
        .build();
    StartConnection(connection);

    connection.on('DocumentStatusUpdated', ProcessDocumentData);

    connection.onclose(function () {
        console.log('disconnected');
        setTimeout(function () { StartConnection(connection); }, 5000);
    });
}).catch(console.error);

有人可以指导我吗?

谢谢

根据您共享的代码,您需要 userIdcompanyId 您想要添加到您的群组的用户,并相应地简单地进行 axios.get() 调用。

要将消息发送到特定组,您还需要一个功能。该文档具有相同的 sample code 。这里也一样供参考

[FunctionName("SendMessage")]
public static Task SendMessage(
    [HttpTrigger(AuthorizationLevel.Anonymous, "post")]object message,
    [SignalR(HubName = "chat")]IAsyncCollector<SignalRMessage> signalRMessages)
{
    return signalRMessages.AddAsync(
        new SignalRMessage
        {
            // the message will be sent to the group with this name
            GroupName = "myGroup",
            Target = "newMessage",
            Arguments = new [] { message }
        });
}

然后您将 axios.post() 调用此端点以向之前创建的群组发送消息。