如何将事件从 Azure SignalR 服务发送到事件网格How to send events from Azure SignalR Service to Event Grid

Azure 事件网格是一个完全托管的事件路由服务,可以通过发布-订阅模型提供一致的事件使用数据。Azure Event Grid is a fully managed event routing service that provides uniform event consumption using a pub-sub model. 在本指南中,我们将使用 Azure CLI 创建 Azure SignalR 服务、订阅连接事件,然后部署一个示例 Web 应用程序来接收事件。In this guide, you use the Azure CLI to create an Azure SignalR Service, subscribe to connection events, then deploy a sample web application to receive the events. 最后,可以连接和断开连接,并可在示例应用程序中查看事件负载。Finally, you can connect and disconnect and see the event payload in the sample application.

如果没有 Azure 订阅,可在开始前创建一个 试用帐户If you don't have an Azure subscription, create a trial account before you begin.

本文中的 Azure CLI 命令已根据 Bash shell 设置了格式。The Azure CLI commands in this article are formatted for the Bash shell. 如果使用其他 shell(例如 PowerShell 或命令提示符),则可能需要相应地调整行连续字符或变量赋值行。If you're using a different shell like PowerShell or Command Prompt, you may need to adjust line continuation characters or variable assignment lines accordingly. 本文使用变量来最大程度地减少所需的命令编辑量。This article uses variables to minimize the amount of command editing required.

创建资源组Create a resource group

Azure 资源组是在其中部署和管理 Azure 资源的逻辑容器。An Azure resource group is a logical container in which you deploy and manage your Azure resources. 以下 az group create 命令在 chinaeast2 区域中创建一个名为 myResourceGroup 的资源组。The following az group create command creates a resource group named myResourceGroup in the chinaeast2 region. 若要对资源组使用不同的名称,请将 RESOURCE_GROUP_NAME 设置为不同的值。If you want to use a different name for your resource group, set RESOURCE_GROUP_NAME to a different value.


az group create --name $RESOURCE_GROUP_NAME --location chinaeast2

创建 SignalR 服务Create a SignalR Service

接下来,使用以下命令将 Azure Signalr 服务部署到资源组中。Next, deploy an Azure Signalr Service into the resource group with the following commands.


az signalr create --resource-group $RESOURCE_GROUP_NAME --name $SIGNALR_NAME --sku Free_F1

创建 SignalR 服务之后,Azure CLI 将返回如下所示的输出:Once the SignalR Service has been created, the Azure CLI returns output similar to the following:

  "externalIp": "",
  "hostName": "clitest.servicedev.signalr.azure.cn",
  "hostNamePrefix": "clitest",
  "id": "/subscriptions/28cf13e2-c598-4aa9-b8c8-098441f0827a/resourceGroups/clitest1/providers/Microsoft.SignalRService/SignalR/clitest",
  "location": "chinaeast2",
  "name": "clitest",
  "provisioningState": "Succeeded",
  "publicPort": 443,
  "resourceGroup": "clitest1",
  "serverPort": 443,
  "sku": {
    "capacity": 1,
    "family": null,
    "name": "Free_F1",
    "size": "F1",
    "tier": "Free"
  "tags": null,
  "type": "Microsoft.SignalRService/SignalR",
  "version": "1.0"

创建事件终结点Create an event endpoint

在本部分,我们使用 GitHub 存储库中的资源管理器模板,将一个预生成的示例 Web 应用程序部署到 Azure 应用服务。In this section, you use a Resource Manager template located in a GitHub repository to deploy a pre-built sample web application to Azure App Service. 稍后,我们将订阅该注册表的事件网格事件,并将此应用指定为事件要发送到的终结点。Later, you subscribe to your registry's Event Grid events and specify this app as the endpoint to which the events are sent.

若要部署示例应用,请将 SITE_NAME 设置为 Web 应用的唯一名称,并执行以下命令。To deploy the sample app, set SITE_NAME to a unique name for your web app, and execute the following commands. 站点名称在 Azure 中必须唯一,因为它是 Web 应用的完全限定域名 (FQDN) 的一部分。The site name must be unique within Azure because it forms part of the fully qualified domain name (FQDN) of the web app. 在稍后的部分,我们将在 Web 浏览器中导航到应用的 FQDN,以查看注册表的事件。In a later section, you navigate to the app's FQDN in a web browser to view your registry's events.


az group deployment create \
    --resource-group $RESOURCE_GROUP_NAME \
    --template-uri "https://raw.githubusercontent.com/Azure-Samples/azure-event-grid-viewer/master/azuredeploy.json" \
    --parameters siteName=$SITE_NAME hostingPlanName=$SITE_NAME-plan

部署成功后(可能需要几分钟时间),打开浏览器并导航到 Web 应用,以确保它正在运行:Once the deployment succeeds (it might take a few minutes), open a browser and navigate to your web app to make sure it's running:


启用事件网格资源提供程序Enable Event Grid resource provider

如果以前未在 Azure 订阅中使用过事件网格,则可能需要注册事件网格资源提供程序。If you haven't previously used Event Grid in your Azure subscription, you may need to register the Event Grid resource provider. 运行以下命令,注册提供程序:Run the following command to register the provider:

az provider register --namespace Microsoft.EventGrid

完成注册可能需要一些时间。It may take a moment for the registration to finish. 若要检查状态,请运行:To check the status, run:

az provider show --namespace Microsoft.EventGrid --query "registrationState"

registrationStateRegistered 后,即可继续。When registrationState is Registered, you're ready to continue.

订阅注册表事件Subscribe to registry events

在事件网格中订阅一个主题,以告知你要跟踪哪些事件,以及要将事件发送到何处。 In Event Grid, you subscribe to a topic to tell it which events you want to track, and where to send them. 以下 az eventgrid event-subscription create 命令订阅创建的 Azure SignalR 服务,并将 Web 应用的 URL 指定为要将事件发送到的终结点。The following az eventgrid event-subscription create command subscribes to the Azure SignalR Service you created, and specifies your web app's URL as the endpoint to which it should send events. 此处可以重复使用在前面几个部分填充的环境变量,因此无需进行编辑。The environment variables you populated in earlier sections are reused here, so no edits are required.

SIGNALR_SERVICE_ID=$(az signalr show --resource-group $RESOURCE_GROUP_NAME --name $SIGNALR_NAME --query id --output tsv)

az eventgrid event-subscription create \
    --name event-sub-signalr \
    --source-resource-id $SIGNALR_SERVICE_ID \
    --endpoint $APP_ENDPOINT

完成订阅后,应会看到如下所示的输出:When the subscription is completed, you should see output similar to the following:

  "deadLetterDestination": null,
  "destination": {
    "endpointBaseUrl": "https://$SITE_NAME.chinacloudsites.cn/api/updates",
    "endpointType": "WebHook",
    "endpointUrl": null
  "filter": {
    "includedEventTypes": [
    "isSubjectCaseSensitive": null,
    "subjectBeginsWith": "",
    "subjectEndsWith": ""
  "id": "/subscriptions/28cf13e2-c598-4aa9-b8c8-098441f0827a/resourceGroups/myResourceGroup/providers/Microsoft.SignalRService/SignalR/SignalRTestSvc/providers/Microsoft.EventGrid/eventSubscriptions/event-sub-signalr",
  "labels": null,
  "name": "event-sub-signalr",
  "provisioningState": "Succeeded",
  "resourceGroup": "myResourceGroup",
  "retryPolicy": {
    "eventTimeToLiveInMinutes": 1440,
    "maxDeliveryAttempts": 30
  "topic": "/subscriptions/28cf13e2-c598-4aa9-b8c8-098441f0827a/resourceGroups/myResourceGroup/providers/microsoft.signalrservice/signalr/SignalRTestSvc",
  "type": "Microsoft.EventGrid/eventSubscriptions"

触发注册表事件Trigger registry events

将服务模式切换到Serverless Mode,设置一个到 SignalR 服务的客户端连接。Switch to the service mode to Serverless Mode and setup a client connection to the SignalR Service. 可以将无服务器示例作为参考。You can take Serverless Sample as a reference.

git clone git@github.com:aspnet/AzureSignalR-samples.git

cd samples/Management

# Start the negotiation server
# Negotiation server is responsible for generating access token for clients
cd NegotitationServer
dotnet user-secrets set Azure:SignalR:ConnectionString "<Connection String>"
dotnet run

# Use a separate command line
# Start a client
cd SignalRClient
dotnet run

查看注册表事件View registry events

现在已将客户端连接到 SignalR 服务。You have now connected a client to the SignalR Service. 导航到事件网格查看器 Web 应用,应会看到 ClientConnectionConnected 事件。Navigate to your Event Grid Viewer web app, and you should see a ClientConnectionConnected event. 如果终止客户端,则还会看到 ClientConnectionDisconnected 事件。If you terminate the client, you will also see a ClientConnectionDisconnected event.