包含: 托管集成 —&—
Client 集成
Azure Database for PostgreSQL—Flexible Server 是基于开放源代码 Postgres 数据库引擎的关系数据库服务。 它是一种完全托管的数据库即服务,可以处理具有可预测性能、安全性、高可用性和动态可伸缩性的任务关键型工作负荷。
Aspire
Azure
PostgreSQL 集成提供了一种连接到现有 AzurePostgreSQL 数据库的方法,或者使用 .NET从 docker.io/library/postgres 创建新实例。
托管集成
托管集成 AspireAzurePostgreSQL 将 PostgreSQL 灵活服务器和数据库建模为 AzurePostgresFlexibleServerResource 和 AzurePostgresFlexibleServerDatabaseResource 类型。 托管集成中固有可用的其他类型的表示在以下资源中:
若要访问这些类型和 API 以将其表示为 AppHost 项目中的资源,请安装 。📦AspireHosting.Azure.PostgreSQLNuGet 包:
dotnet add package Aspire.Hosting.Azure.PostgreSQL
有关详细信息,请参阅 dotnet add package。
Azure PostgreSQL 托管集成依赖于 📦Aspire.Hosting.PostgreSQL NuGet 包,扩展它以支持 Azure。 所有可以用 AspirePostgreSQL 集成 和 AspirePostgreSQLEntity Framework Core 集成 执行的操作,也都可以用这个集成来实现。
添加 AzurePostgreSQL 服务器资源
安装 AspireAzurePostgreSQL 托管集成后,请在 AddAzurePostgresFlexibleServer AppHost 项目中调用扩展方法:
var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddAzurePostgresFlexibleServer("postgres");
var postgresdb = postgres.AddDatabase("postgresdb");
var exampleProject = builder.AddProject<Projects.ExampleProject>()
.WithReference(postgresdb);
上述 AddAzurePostgresFlexibleServer 调用将 PostgreSQL 服务器资源配置为 AzurePostgres 灵活 Server 类型。
重要
默认情况下,AddAzurePostgresFlexibleServer 配置 Microsoft Entra ID 身份验证。 这需要更改需要连接到这些资源的应用程序。 有关详细信息,请参阅 Client 整合。
提示
调用 AddAzurePostgresFlexibleServer时,它会隐式调用 AddAzureProvisioning,这增加了在应用启动期间动态生成 Azure 资源的支持。 应用必须配置相应的订阅和位置。 有关详细信息,请参阅 本地预配:配置。
连接到现有 AzurePostgreSQL 灵活服务器
你可能已有一个现有的灵活服务器 AzurePostgreSQL 并希望连接到它。 链接调用以标注你的 AzurePostgresFlexibleServerResource 是现有资源:
var builder = DistributedApplication.CreateBuilder(args);
var existingPostgresName = builder.AddParameter("existingPostgresName");
var existingPostgresResourceGroup = builder.AddParameter("existingPostgresResourceGroup");
var postgres = builder.AddAzurePostgresFlexibleServer("postgres")
.AsExisting(existingPostgresName, existingPostgresResourceGroup);
builder.AddProject<Projects.ExampleProject>()
.WithReference(postgres);
// After adding all resources, run the app...
重要
调用RunAsExisting或PublishAsExistingAsExisting处理订阅中Azure已存在的资源的方法时,必须将某些配置值添加到 AppHost,以确保Aspire找到它们。 必要的配置值包括 SubscriptionId、 AllowResourceGroupCreation、 ResourceGroup 和 Location。 如果您不设置它们,仪表板中就会出现“缺少配置”错误 Aspire。 有关如何设置它们的详细信息,请参阅 “配置”。
有关将 AzurePostgreSQL 灵活服务器资源视为现有资源的详细信息,请参阅 “使用现有 Azure 资源”。
注释
或者,可以向 AppHost 添加连接字符串,而不是表示 AzurePostgreSQL 灵活的服务器资源。 此方法属于弱类型,不适用于角色分配或基础结构自定义。 有关详细信息,请参阅 添加包含连接字符串的现有 Azure 资源。
以容器身份运行 AzurePostgreSQL 资源
托管集成 AzurePostgreSQL 支持将 PostgreSQL 服务器作为本地容器运行。 这适用于想要在本地运行 PostgreSQL 服务器以进行开发和测试的情况,避免需要预配 Azure 资源或连接到现有 AzurePostgreSQL 服务器。
若要将 PostgreSQL 服务器作为容器运行,请调用 RunAsContainer 方法:
var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddAzurePostgresFlexibleServer("postgres")
.RunAsContainer();
var postgresdb = postgres.AddDatabase("postgresdb");
var exampleProject = builder.AddProject<Projects.ExampleProject>()
.WithReference(postgresdb);
前面的代码将 AzurePostgreSQL 灵活 Server 资源配置为在容器中本地运行。
提示
RunAsContainer 方法可用于本地开发和测试。 API 提供一个可选委托,允许您自定义底层的 PostgresServerResource 配置。 例如,你可以添加 pgAdmin 和 pgWeb,添加数据卷或数据绑定装载,还可以添加初始化绑定装载。 有关详细信息,请参阅 AspirePostgreSQL 托管集成 部分。
将 AzurePostgreSQL 服务器配置为使用密码身份验证
默认情况下,AzurePostgreSQL 服务器配置为使用 Microsoft Entra ID 身份验证。 如果要使用密码身份验证,可以通过调用 WithPasswordAuthentication 方法将服务器配置为使用密码身份验证:
var builder = DistributedApplication.CreateBuilder(args);
var username = builder.AddParameter("username", secret: true);
var password = builder.AddParameter("password", secret: true);
var postgres = builder.AddAzurePostgresFlexibleServer("postgres")
.WithPasswordAuthentication(username, password);
var postgresdb = postgres.AddDatabase("postgresdb");
var exampleProject = builder.AddProject<Projects.ExampleProject>()
.WithReference(postgresdb);
前面的代码将 AzurePostgreSQL 服务器配置为使用密码身份验证。
username参数password作为参数添加到 AppHost,并WithPasswordAuthentication调用该方法将服务器配置为AzurePostgreSQL使用密码身份验证。 有关详细信息,请参阅 外部参数。
预配生成的 Bicep
如果你是 Bicep的新手,它是一种用于定义 Azure 资源的领域专用语言。 使用 Aspire时,无需手动编写 Bicep,因为预配 API 会为你生成 Bicep。 发布应用时,生成的 Bicep 文件将与清单文件一同输出。 添加 AzurePostgreSQL 资源时,会生成以下 Bicep:
@description('The location for the resource(s) to be deployed.')
param location string = resourceGroup().location
resource postgres_flexible 'Microsoft.DBforPostgreSQL/flexibleServers@2024-08-01' = {
name: take('postgresflexible-${uniqueString(resourceGroup().id)}', 63)
location: location
properties: {
authConfig: {
activeDirectoryAuth: 'Enabled'
passwordAuth: 'Disabled'
}
availabilityZone: '1'
backup: {
backupRetentionDays: 7
geoRedundantBackup: 'Disabled'
}
highAvailability: {
mode: 'Disabled'
}
storage: {
storageSizeGB: 32
}
version: '16'
}
sku: {
name: 'Standard_B1ms'
tier: 'Burstable'
}
tags: {
'aspire-resource-name': 'postgres-flexible'
}
}
resource postgreSqlFirewallRule_AllowAllAzureIps 'Microsoft.DBforPostgreSQL/flexibleServers/firewallRules@2024-08-01' = {
name: 'AllowAllAzureIps'
properties: {
endIpAddress: '0.0.0.0'
startIpAddress: '0.0.0.0'
}
parent: postgres_flexible
}
output connectionString string = 'Host=${postgres_flexible.properties.fullyQualifiedDomainName}'
output name string = postgres_flexible.name
前面的 Bicep 是预配灵活服务器资源的模块 AzurePostgreSQL 。 此外,在单独的模块中为 Azure 资源创建角色分配:
@description('The location for the resource(s) to be deployed.')
param location string = resourceGroup().location
param postgres_flexible_outputs_name string
param principalType string
param principalId string
param principalName string
resource postgres_flexible 'Microsoft.DBforPostgreSQL/flexibleServers@2024-08-01' existing = {
name: postgres_flexible_outputs_name
}
resource postgres_flexible_admin 'Microsoft.DBforPostgreSQL/flexibleServers/administrators@2024-08-01' = {
name: principalId
properties: {
principalName: principalName
principalType: principalType
}
parent: postgres_flexible
}
除了 PostgreSQL 灵活服务器,它还预配 Azure 防火墙规则以允许所有 Azure IP 地址。 最后,将为 PostgreSQL 服务器创建管理员,连接字符串将输出为输出变量。 生成的 Bicep 是一个起点,并受到 C# 中预配基础结构变化的影响。 对 Bicep 文件进行的自定义将直接被覆盖,因此请通过 C# 预配 API 进行更改,以确保它们反映在生成的文件中。
自定义预配基础结构
所有 AspireAzure 资源都是 AzureProvisioningResource 类型的子类。 这类型通过使用 Azure API 提供用于配置 ConfigureInfrastructure<T>(IResourceBuilder<T>, Action<AzureResourceInfrastructure>) 资源的流畅 API 来允许自定义生成的 Bicep。 例如,可以配置 kind、consistencyPolicy、locations等。 以下示例演示如何自定义 PostgreSQL 服务器资源:
builder.AddAzurePostgresFlexibleServer("postgres")
.ConfigureInfrastructure(infra =>
{
var flexibleServer = infra.GetProvisionableResources()
.OfType<PostgreSqlFlexibleServer>()
.Single();
flexibleServer.Sku = new PostgreSqlFlexibleServerSku
{
Tier = PostgreSqlFlexibleServerSkuTier.Burstable,
};
flexibleServer.HighAvailability = new PostgreSqlFlexibleServerHighAvailability
{
Mode = PostgreSqlFlexibleServerHighAvailabilityMode.ZoneRedundant,
StandbyAvailabilityZone = "2",
};
flexibleServer.Tags.Add("ExampleKey", "Example value");
});
前面的代码:
- 链接对 ConfigureInfrastructure API 的调用:
-
infra参数是 AzureResourceInfrastructure 类型的实例。 - 通过调用 GetProvisionableResources() 方法检索可预配资源。
- 系统会检索单个 PostgreSqlFlexibleServer。
- 使用
sku设置 PostgreSqlFlexibleServerSkuTier.Burstable。 - 在备用可用性区域 PostgreSqlFlexibleServerHighAvailabilityMode.ZoneRedundant中,高可用性属性已设置为
"2"。 - 一个标记被添加到灵活服务器,其键为
ExampleKey,值为Example value。
-
还有更多配置选项可用于自定义 PostgreSQL 灵活服务器资源。 有关详细信息,请参阅 Azure.Provisioning.PostgreSql 和 Azure。预配自定义。
Client 集成
若要开始进行AspireAzurePostgreSQL客户端集成,请在使用客户端的项目(即使用📦客户端的应用程序对应的项目)中安装Aspire.Npgsql NuGet 包。 PostgreSQL 客户端集成会注册一个 NpgsqlDataSource 实例,以便您可以用来与 PostgreSQL交互。
dotnet add package Aspire.Azure.Npgsql
可以通过客户端集成来使用 PostgreSQL 连接,方法是调用 AddAzureNpgsqlDataSource。
builder.AddAzureNpgsqlDataSource(connectionName: "postgresdb");
提示
参数 connectionName 必须与在 AppHost 项目中添加 PostgreSQL 服务器资源时使用的名称匹配。
前面的代码片段演示如何使用 AddAzureNpgsqlDataSource 该方法注册 NpgsqlDataSource 使用 Azure 身份验证的实例(Microsoft Entra ID)。 此 "postgresdb" 连接名称对应于连接字符串配置值。
将 NpgsqlDataSource 添加到生成器后,可以使用依赖项注入获取 NpgsqlDataSource 实例。 例如,若要从示例服务中检索数据源对象,请将其定义为构造函数参数,并确保 ExampleService 类注册到依赖项注入容器:
public class ExampleService(NpgsqlDataSource dataSource)
{
// Use dataSource...
}
有关依赖项注入的详细信息,请参阅 .NET 依赖项注入。
添加键控 Azure Npgsql 客户端
在某些情况下,可能需要使用不同的连接名称注册多个 NpgsqlDataSource 实例。 若要注册密钥 Npgsql 客户端,请调用 AddKeyedAzureNpgsqlDataSource 方法:
builder.AddKeyedAzureNpgsqlDataSource(name: "sales_db");
builder.AddKeyedAzureNpgsqlDataSource(name: "inventory_db");
然后,可以使用依赖项注入检索 NpgsqlDataSource 实例。 例如,若要从示例服务检索连接,
public class ExampleService(
[FromKeyedServices("sales_db")] NpgsqlDataSource salesDataSource,
[FromKeyedServices("inventory_db")] NpgsqlDataSource inventoryDataSource)
{
// Use data sources...
}
有关密钥服务的详细信息,请参阅 .NET 依赖项注入:键式服务。
配置
Aspire Azure Npgsql 集成提供了多个选项,用于根据项目的要求和约定配置数据库连接。
使用连接字符串
使用配置节中 ConnectionStrings 定义的连接字符串时,在调用 AddAzureNpgsqlDataSource时提供连接字符串的名称:
builder.AddAzureNpgsqlDataSource("postgresdb");
从ConnectionStrings配置部分检索连接字符串。例如,请考虑以下JSON配置:
{
"ConnectionStrings": {
"postgresdb": "Host=myserver;Database=test"
}
}
有关如何配置连接字符串的详细信息,请参阅 Npgsql 连接字符串文档。
注释
用户名和密码会自动从设置中提供的凭据推断。
使用配置提供程序
Aspire
Azure Npgsql 集成支持 Microsoft.Extensions.Configuration。 它使用 AzureNpgsqlSettings 键从配置中加载 Aspire:Azure:Npgsql。 例如,请考虑以下 appsettings.json 文件,该文件配置了一些可用选项:
{
"Aspire": {
"Npgsql": {
"DisableHealthChecks": true,
"DisableTracing": true
}
}
}
使用内联委托
你可以在代码中配置设置,方法是传递 Action<AzureNpgsqlSettings> configureSettings 委托,从而以内联方式设置部分或全部选项,例如通过代码禁用运行状况检查:
builder.AddAzureNpgsqlDataSource(
"postgresdb",
settings => settings.DisableHealthChecks = true);
使用 AzureNpgsqlSettings.Credential 属性建立连接。 如果未配置凭据,则使用 DefaultAzureCredential。 当连接字符串包含用户名和密码时,将忽略凭据。
Client 集成运行状况检查
默认情况下, Aspire客户端集成 为所有服务启用了 运行状况检查 。 同样,许多 Aspire托管集成 还启用健康检查端点。 有关详细信息,请参阅:
- 添加
NpgSqlHealthCheck,用于验证命令是否能够成功执行在基础 Postgres 数据库上。 - 与
/healthHTTP 终结点集成,该终结点规定所有注册的健康检查必须通过,才能将应用视为已准备好接受流量。
可观测性和遥测
Aspire 集成会自动设置日志记录、跟踪和指标配置,这些配置有时称为 可观测性支柱。 有关集成可观测性和遥测的详细信息,请参阅 Aspire 集成概述。 根据支持服务,某些集成可能仅支持其中一些功能。 例如,某些集成支持日志记录和跟踪,但不支持指标。 也可以使用 配置 部分中介绍的技术禁用遥测功能。
日志记录
Aspire PostgreSQL 集成使用以下日志类别:
Npgsql.ConnectionNpgsql.CommandNpgsql.TransactionNpgsql.CopyNpgsql.ReplicationNpgsql.Exception
跟踪
Aspire PostgreSQL 集成将使用 OpenTelemetry 来产生以下追踪活动:
Npgsql
指标
Aspire PostgreSQL 集成将使用 OpenTelemetry发出以下指标:
- Npgsql:
ec_Npgsql_bytes_written_per_secondec_Npgsql_bytes_read_per_secondec_Npgsql_commands_per_secondec_Npgsql_total_commandsec_Npgsql_current_commandsec_Npgsql_failed_commandsec_Npgsql_prepared_commands_ratioec_Npgsql_connection_poolsec_Npgsql_multiplexing_average_commands_per_batchec_Npgsql_multiplexing_average_write_time_per_batch