.NET Aspire Azure Web PubSub 集成

包含:托管集成已包含 - Client 集成已包含Client 集成

Azure Web PubSub 是一项完全托管的实时消息传送服务,可用于使用 WebSocket 和发布-订阅模式生成实时 Web 应用程序。 通过 .NET AspireAzureWeb PubSub 集成,可以从 Azure 应用程序连接到 Web PubSub.NET 实例。

托管集成

托管集成 .NET.NET AspireAzure Web PubSub 将 Web PubSub 资源建模为以下类型:

  • AzureWebPubSubResource:表示 AzureWeb PubSub 资源,包括与基础 Azure 资源的连接信息。
  • AzureWebPubSubHubResource:表示一种 Web PubSub 中心配置资源,其中包含中心的设置。 例如,可以指定中心是否允许匿名连接或向中心添加事件处理程序。

若要访问这些类型和 API 以在 应用主机 项目中使用它们,请安装 📦Aspire.Hosting.Azure.WebPubSub NuGet 包:

dotnet add package Aspire.Hosting.Azure.WebPubSub

有关详细信息,请参阅 dotnet add package在 .NET 应用程序中管理包依赖关系

添加 AzureWeb PubSub 资源

若要将 AzureWeb PubSub 资源添加到应用主机项目,请调用提供名称的 AddAzureWebPubSub 方法:

var builder = DistributedApplication.CreateBuilder(args);

var webPubSub = builder.AddAzureWebPubSub("web-pubsub");

builder.AddProject<Projects.ExampleProject>()
       .WithReference(webPubSub);

// After adding all resources, run the app...

前面的代码将名为 Azure 的 Web PubSubweb-pubsub 资源添加到应用主机项目中。 WithReference 方法将连接信息传递给 ExampleProject 项目。

重要

调用 AddAzureWebPubSub时,它会隐式调用 AddAzureProvisioning(IDistributedApplicationBuilder),这增加了在应用启动期间动态生成 Azure 资源的支持。 应用程序必须配置相应的订阅和位置。 有关详细信息,请参阅 本地预配:配置

添加 AzureWeb PubSub 中心资源

添加 AzureWeb PubSub 资源时,还可以添加子中心资源。 中心资源是连接和事件处理程序的逻辑分组。 要在您的应用主机项目中添加AzureWeb PubSub中心资源,请通过调用AddHub方法来提供资源和中心名称。

var builder = DistributedApplication.CreateBuilder(args);

var worker = builder.AddProject<Projects.WorkerService>("worker")
                    .WithExternalHttpEndpoints();

var webPubSub = builder.AddAzureWebPubSub("web-pubsub");
var messagesHub = webPubSub.AddHub(name: "messages", hubName: "messageHub");

// After adding all resources, run the app...

前面的代码添加了一个名为Azure的中心资源和一个中心名称Web PubSub,这使能够添加事件处理程序。 若要添加事件处理程序,请调用 AddEventHandler

var builder = DistributedApplication.CreateBuilder(args);

var worker = builder.AddProject<Projects.WorkerService>("worker")
                    .WithExternalHttpEndpoints();

var webPubSub = builder.AddAzureWebPubSub("web-pubsub");
var messagesHub = webPubSub.AddHub(name: "messages", hubName: "messageHub");

messagesHub.AddEventHandler(
    $"{worker.GetEndpoint("https")}/eventhandler/",
    systemEvents: ["connected"]);

// After adding all resources, run the app...

前面的代码添加了一个命名为 worker 的工作服务项目,并带有一个外部 HTTP 终结点。 名为 messages 资源的中心将添加到 web-pubsub 资源,并将事件处理程序添加到 messagesHub 资源。 事件处理程序 URL 设置为工作服务的外部 HTTP 终结点。 有关详细信息,请参阅 AzureWeb PubSub 事件处理程序

由预配生成的 Bicep

发布应用时,.NET.NET Aspire 配置 API 会和清单文件一起生成 Bicep。 Bicep 是一种特定于域的语言,用于定义 Azure 资源。 有关详细信息,请参阅 Bicep 概述

添加AzureWeb PubSub资源时,系统会生成以下Bicep 脚本:

@description('The ___location for the resource(s) to be deployed.')
param ___location string = resourceGroup().___location

param sku string = 'Free_F1'

param capacity int = 1

param messages_url_0 string

resource web_pubsub 'Microsoft.SignalRService/webPubSub@2024-03-01' = {
  name: take('webpubsub-${uniqueString(resourceGroup().id)}', 63)
  ___location: ___location
  sku: {
    name: sku
    capacity: capacity
  }
  tags: {
    'aspire-resource-name': 'web-pubsub'
  }
}

resource messages 'Microsoft.SignalRService/webPubSub/hubs@2024-03-01' = {
  name: 'messages'
  properties: {
    eventHandlers: [
      {
        urlTemplate: messages_url_0
        userEventPattern: '*'
        systemEvents: [
          'connected'
        ]
      }
    ]
  }
  parent: web_pubsub
}

output endpoint string = 'https://${web_pubsub.properties.hostName}'

output name string = web_pubsub.name

上述的 Bicep 模块是用于预配 AzureWeb PubSub 资源的。 此外,在单独的模块中为 Azure 资源创建角色分配:

@description('The ___location for the resource(s) to be deployed.')
param ___location string = resourceGroup().___location

param web_pubsub_outputs_name string

param principalType string

param principalId string

resource web_pubsub 'Microsoft.SignalRService/webPubSub@2024-03-01' existing = {
  name: web_pubsub_outputs_name
}

resource web_pubsub_WebPubSubServiceOwner 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
  name: guid(web_pubsub.id, principalId, subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '12cf5a90-567b-43ae-8102-96cf46c7d9b4'))
  properties: {
    principalId: principalId
    roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '12cf5a90-567b-43ae-8102-96cf46c7d9b4')
    principalType: principalType
  }
  scope: web_pubsub
}

生成的 Bicep 作为起点,受 C# 中资源配置基础设施更改的影响。 直接对 Bicep 文件的自定义项所做的更改将被覆盖,因此请通过 C# 预配 API 进行更改,以确保它们反映在生成的文件中。

自定义预配基础结构

所有 .NET AspireAzure 资源都是 AzureProvisioningResource 类型的子类。 此类型提供了一种流畅的 API,可以通过 Azure API 来配置 ConfigureInfrastructure<T>(IResourceBuilder<T>, Action<AzureResourceInfrastructure>) 资源,从而实现对生成的 Bicep 的自定义。 例如,可以配置 kindconsistencyPolicylocations等。 以下示例演示如何自定义 AzureAzure Cosmos DB 资源:

builder.AddAzureWebPubSub("web-pubsub")
    .ConfigureInfrastructure(infra =>
    {
        var webPubSubService = infra.GetProvisionableResources()
                                    .OfType<WebPubSubService>()
                                    .Single();

        webPubSubService.Sku.Name = "Standard_S1";
        webPubSubService.Sku.Capacity = 5;
        webPubSubService.Tags.Add("ExampleKey", "Example value");
    });

前面的代码:

还有更多配置选项可用于自定义 Web PubSub 资源。 有关详细信息,请参阅 Azure.Provisioning.WebPubSub。 有关详细信息,请参阅 Azure.Provisioning 自定义设置

连接到现有 AzureWeb PubSub 实例

你可能有一个现有的 AzureWeb PubSub 服务想要连接。 可以链式调用以标注 AzureWebPubSubResource 是现有资源。

var builder = DistributedApplication.CreateBuilder(args);

var existingPubSubName = builder.AddParameter("existingPubSubName");
var existingPubSubResourceGroup = builder.AddParameter("existingPubSubResourceGroup");

var webPubSub = builder.AddAzureWebPubSub("web-pubsub")
                       .AsExisting(existingPubSubName, existingPubSubResourceGroup);

builder.AddProject<Projects.ExampleProject>()
       .WithReference(webPubSub);

// After adding all resources, run the app...

有关将 AzureWeb PubSub 资源视为现有资源的详细信息,请参阅 使用现有 Azure 资源

或者,您可以向应用主机添加连接字符串来代替表示 AzureWeb PubSub 资源。 这是一种仅依赖于 string 值的弱类型化方法。 若要向现有 AzureWeb PubSub 服务添加连接,请调用 AddConnectionString 方法:

var builder = DistributedApplication.CreateBuilder(args);

var webPubSub = builder.ExecutionContext.IsPublishMode
    ? builder.AddAzureWebPubSub("web-pubsub")
    : builder.AddConnectionString("web-pubsub");

builder.AddProject<Projects.ExampleProject>()
       .WithReference(webPubSub);

// After adding all resources, run the app...

注释

连接字符串用于表示各种连接信息,包括数据库连接、消息代理、终结点 URI 和其他服务。 在 .NET.NET Aspire 名词中,术语“连接字符串”用于表示任何类型的连接信息。

连接字符串在应用主机的配置(通常位于用户机密)的 ConnectionStrings 部分下进行配置:

{
  "ConnectionStrings": {
    "web-pubsub": "https://{account_name}.webpubsub.azure.com"
  }
}

有关详细信息,请参阅 添加带有连接字符串的现有Azure资源

Client 集成

.NET Aspire Azure Web PubSub 客户端集成用于通过 Azure 连接到 Web PubSubWebPubSubServiceClient 服务。 若要开始 .NET AspireAzureWeb PubSub 服务客户端集成,请安装 📦Aspire。Azure。Messaging.WebPubSub 应用程序中的 NuGet 包。

dotnet add package Aspire.Azure.Messaging.WebPubSub

支持的 Web PubSub 客户端类型

库支持以下 Web PubSub 客户端类型:

Azure 客户端类型 Azure 选项类别 .NET .NET Aspire 设置类
WebPubSubServiceClient WebPubSubServiceClientOptions AzureMessagingWebPubSubSettings

添加 Web PubSub 客户端

在客户端使用项目的 Program.cs 文件中,调用 AddAzureWebPubSubServiceClient 扩展方法注册 WebPubSubServiceClient,以便通过依赖注入容器使用。 该方法采用连接名称参数:

builder.AddAzureWebPubSubServiceClient(
    connectionName: "web-pubsub");

小提示

connectionName 参数必须与在应用主机项目中添加 Web PubSub 资源时使用的名称匹配。 有关详细信息,请参阅 添加 AzureWeb PubSub 资源

添加 WebPubSubServiceClient后,可以使用依赖项注入检索客户端实例。 例如,若要从示例服务中检索数据源对象,请将其定义为构造函数参数,并确保 ExampleService 类注册到依赖项注入容器:

public class ExampleService(WebPubSubServiceClient client)
{
    // Use client...
}

有关详细信息,请参阅:

添加已加密的Web PubSub客户端

在某些情况下,可能需要使用不同的连接名称注册多个 WebPubSubServiceClient 实例。 若要注册密钥 Web PubSub 客户端,请调用 AddKeyedAzureWebPubSubServiceClient 方法:

builder.AddKeyedAzureWebPubSubServiceClient(name: "messages");
builder.AddKeyedAzureWebPubSubServiceClient(name: "commands");

重要

使用键控服务时,预计应在您的 Web PubSub 资源中配置两个命名中心,一个用于 messages,一个用于 commands

然后,可以使用依赖项注入检索客户端实例。 例如,若要从服务检索客户:

public class ExampleService(
    [KeyedService("messages")] WebPubSubServiceClient messagesClient,
    [KeyedService("commands")] WebPubSubServiceClient commandsClient)
{
    // Use clients...
}

如果要将单个 WebPubSubServiceClient 实例注册到特定的连接名称,则存在一个重载,该重载使用连接名称作为服务密钥。 调用 AddKeyedAzureWebPubSubServiceClient 方法。 此方法将客户端注册为依赖项注入容器中的单例服务。

builder.AddKeyedAzureWebPubSubServiceClient(connectionName: "web-pubsub");

有关详细信息,请参阅 .NET中的键控服务

配置

.NET Aspire Azure Web PubSub 库提供了多个选项,用于根据项目的要求和约定配置 AzureWeb PubSub 连接。 必须提供 EndpointConnectionString

使用连接字符串

使用 ConnectionStrings 配置部分中的连接字符串时,可以在调用 AddAzureWebPubSubServiceClient时提供连接字符串的名称:

builder.AddAzureWebPubSubServiceClient(
    "web-pubsub",
    settings => settings.HubName = "your_hub_name");

ConnectionStrings 配置部分检索连接信息。 支持两种连接格式:

  • 服务端点(推荐):使用DefaultAzureCredential的服务端点。

    {
      "ConnectionStrings": {
        "web-pubsub": "https://{account_name}.webpubsub.azure.com"
      }
    }
    
  • 连接字符串:包括访问密钥。

    {
      "ConnectionStrings": {
        "web-pubsub": "Endpoint=https://{account_name}.webpubsub.azure.com;AccessKey={account_key}"
      }
    }
    

使用配置提供程序

该库支持 Microsoft.Extensions.Configuration。 它从配置中使用 Aspire:Azure:Messaging:WebPubSub 键加载设置:

{
  "Aspire": {
    "Azure": {
      "Messaging": {
        "WebPubSub": {
          "DisableHealthChecks": true,
          "HubName": "your_hub_name"
        }
      }
    }
  }
}

有关完整的 AzureOpenAI 客户端集成 JSON 架构,请参阅 Aspire.Azure.Messaging.WebPubSub/ConfigurationSchema.json

使用内联委托

您可以直接在界面中配置设置:

builder.AddAzureWebPubSubServiceClient(
    "web-pubsub",
    settings => settings.DisableHealthChecks = true);

可观测性和遥测

.NET .NET Aspire 集成会自动设置日志记录、跟踪和指标配置,这些配置有时称为 可观测性的支柱。 有关集成可观测性和遥测的详细信息,请参阅 .NET.NET Aspire 集成概述。 根据支持服务,某些集成可能仅支持其中一些功能。 例如,某些集成支持日志记录和跟踪,但不支持指标。 也可以使用 配置 部分中介绍的技术禁用遥测功能。

伐木

.NET Aspire Azure Web PubSub 集成使用以下日志类别:

  • Azure
  • Azure.Core
  • Azure.Identity
  • Azure.Messaging.WebPubSub

描图

.NET Aspire Azure Web PubSub 集成将使用 OpenTelemetry发出以下跟踪活动:

  • Azure.Messaging.WebPubSub.*

指标

由于 .NET Aspire SDK for Azure的限制,Web PubSubAzure.NET 集成目前不默认支持指标。 如果将来发生此更改,将更新此部分以反映这些更改。

另请参阅