如何从 Azure Functions 创建到 SignalR 服务的输出绑定?

How can I create an output binding to SignalR Service from Azure Functions?

我正在尝试实现一个实时聊天应用程序。执行协商功能后,客户端将消息添加到 Cosmos 集合。

https://docs.microsoft.com/en-us/azure/azure-signalr/signalr-concept-azure-functions

  1. A change is made in a Cosmos DB collection

  2. The change event is propagated to the Cosmos DB change feed

  3. An Azure Functions is triggered by the change event using the Cosmos DB trigger

  4. The SignalR Service output binding publishes a message to SignalR Service

  5. SignalR Service publishes the message to all connected clients

我已经完成了前 3 个步骤,但我卡在了第 4 步。是否有任何代码示例演示如何在触发器和 SignalR 服务之间设置 SignalR 输出绑定?我正在使用 C#,理想情况下想要一个仅使用属性的示例(即没有 json 配置)。

这里有一个如何从 Azure 函数向 SignalR 发送消息的示例: https://docs.microsoft.com/en-us/azure/azure-signalr/signalr-concept-serverless-development-config

您可以像这样使用 Azure SignalR output binding 将 Cosmos DB Change Feed 连接到 SignalR:

public static async Task Run(
    [CosmosDBTrigger(
        databaseName: "your-monitored-db",
        collectionName: "your-monitored-collection",
        ConnectionStringSetting = "CosmosConnectionStringSettingName",
        LeaseCollectionName = "leases")]
        IReadOnlyList<Document> events,
    [SignalR(HubName = "events", ConnectionStringSetting = "SignalRConnectionStringSettingName")] 
        IAsyncCollector<SignalRMessage> signalRMessages,
    ILogger log)
{
    await signalRMessages.AddAsync(new SignalRMessage()
    {
        Target = "nameOfTheSignalRHub",
        Arguments = new[] {
            events.Select(singleEvent => JsonConvert.DeserializeObject<YourEventClass>(singleEvent.ToString()))
        }
    });
}

请参阅 this repo 以获取使用您提出的体系结构的完整解决方案。