快速入门指南:使用 Java 的 Azure SDK 库来创建、更新和删除 Azure Database for PostgreSQL - 灵活服务器

本快速入门介绍如何使用 Azure SDK for Java 创建、更新和删除 Azure Database for PostgreSQL 灵活服务器实例。 代码示例是用 Java 编写的,并使用 Azure SDK 库与 Azure Database for PostgreSQL 灵活服务器服务进行交互。

Azure SDK for Java 提供了一组库,可用于使用 Java 与 Azure 服务交互。 SDK 提供一致的编程模型,简化了使用 Azure 服务(包括 Azure Database for PostgreSQL 灵活服务器)的用法。

先决条件

Azure Java SDK 支持的操作

Azure SDK for Java 为 Azure Databases for PostgreSQL 灵活服务器提供了支持这些操作的 azure-resourcemanager-postgresqlflexibleserver 依赖项。

  • 创建 Azure Database for PostgreSQL 灵活服务器
    可以使用指定的配置(例如位置、SKU、存储和版本)创建新的 Azure PostgreSQL 灵活服务器实例。

  • 更新“Azure Database for PostgreSQL”灵活服务器
    可以更新现有的 Azure PostgreSQL 灵活服务器,包括更改管理员登录、密码、SKU、存储和版本等配置。

  • 删除 Azure Database for PostgreSQL 灵活服务器

  • 检索 Azure Database for PostgreSQL 灵活服务器信息
    可以检索有关现有 Azure PostgreSQL 灵活服务器的详细信息,包括其配置、状态和其他元数据。

  • 管理数据库
    可以在 Azure PostgreSQL 灵活服务器实例中创建、更新、删除和检索数据库。

  • 管理防火墙规则
    可以为实例创建、更新、删除和检索防火墙规则来控制访问。

  • 管理配置设置
    可以管理 Azure PostgreSQL 灵活服务器实例的配置设置,包括检索和更新服务器参数。

使用 az cli 设置帐户

在使用 Azure SDK for Java 创建、更新或删除 Azure Database for PostgreSQL 灵活服务器实例之前,必须使用 Azure CLI 登录到 Azure 帐户。

使用 az CLI 登录到帐户

az login

提取帐户的租户 ID,因为后面的代码需要用到它。

az account show --query tenantId --output tsv

创建项目

在首选 IDE 中创建新的 Maven 项目,并为 Azure Database for PostgreSQL 灵活服务器库添加依赖项。

创建 Maven 项目后,一个 pom.xml 文件将被创建。 确保在此文件的 <dependencies> 标记下添加所有依赖项。

<dependency>
 <groupId>com.azure</groupId>
 <artifactId>azure-core-management</artifactId>
 <version>1.17.0</version>
</dependency>
<dependency>
 <groupId>com.azure</groupId>
 <artifactId>azure-identity</artifactId>
 <version>1.15.3</version>
 <scope>compile</scope>
</dependency>
<dependency>
 <groupId>com.azure.resourcemanager</groupId>
 <artifactId>azure-resourcemanager-resources</artifactId>
 <version>2.48.0</version>
</dependency>
 <dependency>
 <groupId>com.azure.resourcemanager</groupId>
 <artifactId>azure-resourcemanager-postgresqlflexibleserver</artifactId>
 <version>1.1.0</version>
</dependency>
<dependency>
 <groupId>com.azure</groupId>
 <artifactId>azure-core-http-netty</artifactId>
 <version>1.15.11</version>
</dependency>
<dependency>
 <groupId>org.apache.logging.log4j</groupId>
 <artifactId>log4j-slf4j-impl</artifactId>
 <version>2.20.0</version>
</dependency>

注释

在将依赖项添加到文件之前,请检查所有依赖项的最新版本。

创建 Azure Database for PostgreSQL 实例

若要创建 Azure PostgreSQL 灵活服务器实例,请创建一个名为 CreateServer.java 以下代码的文件。

package com.example.restservice;
import java.util.HashMap;
import java.util.Map;

import com.azure.core.credential.TokenCredential;
import com.azure.core.http.policy.HttpLogDetailLevel;
import com.azure.core.http.policy.HttpLogOptions;
import com.azure.core.management.AzureEnvironment;
import com.azure.core.management.profile.AzureProfile;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.resourcemanager.postgresqlflexibleserver.PostgreSqlManager;
import com.azure.resourcemanager.postgresqlflexibleserver.models.ActiveDirectoryAuthEnum;
import com.azure.resourcemanager.postgresqlflexibleserver.models.ArmServerKeyType;
import com.azure.resourcemanager.postgresqlflexibleserver.models.AuthConfig;
import com.azure.resourcemanager.postgresqlflexibleserver.models.DataEncryption;
import com.azure.resourcemanager.postgresqlflexibleserver.models.HighAvailability;
import com.azure.resourcemanager.postgresqlflexibleserver.models.HighAvailabilityMode;
import com.azure.resourcemanager.postgresqlflexibleserver.models.IdentityType;
import com.azure.resourcemanager.postgresqlflexibleserver.models.PasswordAuthEnum;
import com.azure.resourcemanager.postgresqlflexibleserver.models.Server;
import com.azure.resourcemanager.postgresqlflexibleserver.models.ServerVersion;
import com.azure.resourcemanager.postgresqlflexibleserver.models.Sku;
import com.azure.resourcemanager.postgresqlflexibleserver.models.SkuTier;
import com.azure.resourcemanager.postgresqlflexibleserver.models.Storage;
import com.azure.resourcemanager.postgresqlflexibleserver.models.UserAssignedIdentity;
public class CreateServer {
    public static void main(String[] args) throws Exception {
              String subscriptionId = "<subscription-id>";
              AzureProfile profile = new AzureProfile("<tenant-id>", subscriptionId, AzureEnvironment.AZURE_CHINA);
             
              TokenCredential credential = new DefaultAzureCredentialBuilder()
              .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()).build();
              PostgreSqlManager manager = PostgreSqlManager.authenticate(credential, profile);
              Server server = manager.servers()
              .define("<server-name>")
              .withRegion("<location>")
              .withExistingResourceGroup("<resource-group-name>")
              .withSku(new Sku().withName("Standard_D4ds_v5").withTier(SkuTier.GENERAL_PURPOSE))
              .withAuthConfig(new AuthConfig().withActiveDirectoryAuth(ActiveDirectoryAuthEnum.DISABLED)
              .withPasswordAuth(PasswordAuthEnum.ENABLED))
              .withIdentity(new UserAssignedIdentity().withType(IdentityType.NONE))
              .withDataEncryption(new DataEncryption().withType(ArmServerKeyType.SYSTEM_MANAGED))
              .withVersion(ServerVersion.ONE_SIX).withAuthConfig(null)
              .withAdministratorLogin("<user-name>")
              .withAdministratorLoginPassword("<password>").withStorage(new Storage().withStorageSizeGB(32))
              .withHighAvailability(new HighAvailability().withMode(HighAvailabilityMode.DISABLED))
              .create();
              System.out.println("Azure Database for PostgreSQL Flexible server instance is created with server name"+server.name());
    }   
}

此示例演示如何使用 PostgreSqlManager 类创建 Azure Database for PostgreSQL 灵活实例服务器。 在调用 create 方法之前,它会使用 TokenCredential 和 AzureProfile 进行身份验证。 身份验证后,它会使用指定的配置定义 Azure PostgreSQL 灵活服务器实例。

将代码中的以下参数替换为你的数据:

  • subscription-id:Azure 订阅 ID。
  • tenant-id :Microsoft Entra 帐户的租户标识。 可以从门户或使用 CLI 获取此信息
  • resource-group-name:资源组的名称。
  • server-name:PostgreSQL 服务器的唯一名称。
  • location:服务器的 Azure 区域。
  • admin-username:管理员用户名。
  • admin-password:管理员密码。

身份验证

可通过不同的方式对凭据进行身份验证。 在此示例中,我们用于 DefaultAzureCredentialBuilder 配置和创建 TokenCredential 对象,该对象是可用于向 Azure 服务进行身份验证的凭据。 使用 Azure CLI 登录,如先决条件中所述。

运行该文件

请确保已创建 maven 项目并执行以下命令;请确保每次在 pom.xml 文件中添加新依赖项以在本地存储库中安装该依赖项时运行以下命令:

mvn clean install

若要运行该文件,可以使用 IDE 运行此代码或使用命令行运行 Java 文件。

javac <file-name>.java
java <file-name>

注释

运行此代码会初始化实例创建过程,此过程可能需要几分钟才能完成。

可以通过 Azure 门户、Azure CLI、Azure PowerShell 和其他各种工具查看部署的 Azure PostgreSQL 灵活服务器实例,以验证部署并查看部署的资源。

创建数据库

可以将新数据库添加到新创建的服务器。 确保 Azure Database for PostgreSQL 灵活服务器实例已启动并运行。

package com.example.restservice;

import com.azure.core.credential.TokenCredential;
import com.azure.core.http.policy.HttpLogDetailLevel;
import com.azure.core.http.policy.HttpLogOptions;
import com.azure.core.management.AzureEnvironment;
import com.azure.core.management.profile.AzureProfile;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.resourcemanager.postgresqlflexibleserver.PostgreSqlManager;

public class CreateDatabaseSample {
    public static void main(String args[]) {
        String subscriptionId = "<subscription-id>";
        AzureProfile profile = new AzureProfile("<tenant-id>", subscriptionId, AzureEnvironment.AZURE_CHINA);
        
        TokenCredential credential = new DefaultAzureCredentialBuilder()
        .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()).build();
        PostgreSqlManager manager = PostgreSqlManager.authenticate(credential, profile);
        manager.databases()
        .define("<database-name>")
        .withExistingFlexibleServer("<resource-group-name>", "<server-name>")
        .withCharset("utf8")
        .withCollation("en_US.utf8")
        .create();
    }
}

更新服务器数据

创建 UpdateServer.java 文件。

还可以通过从postgresqlflexibleserver库调用update()方法来使用此 Java SDK 更新服务器数据。

使用此方法 update ,可以更新版本、管理员用户名、密码等。

package com.example.restservice;

import com.azure.core.credential.TokenCredential;
import com.azure.core.http.policy.HttpLogDetailLevel;
import com.azure.core.http.policy.HttpLogOptions;
import com.azure.core.management.AzureEnvironment;
import com.azure.core.management.profile.AzureProfile;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.resourcemanager.postgresqlflexibleserver.PostgreSqlManager;
import com.azure.resourcemanager.postgresqlflexibleserver.models.ActiveDirectoryAuthEnum;
import com.azure.resourcemanager.postgresqlflexibleserver.models.AuthConfig;
import com.azure.resourcemanager.postgresqlflexibleserver.models.AzureManagedDiskPerformanceTiers;
import com.azure.resourcemanager.postgresqlflexibleserver.models.Backup;
import com.azure.resourcemanager.postgresqlflexibleserver.models.CreateModeForUpdate;
import com.azure.resourcemanager.postgresqlflexibleserver.models.PasswordAuthEnum;
import com.azure.resourcemanager.postgresqlflexibleserver.models.Server;
import com.azure.resourcemanager.postgresqlflexibleserver.models.Sku;
import com.azure.resourcemanager.postgresqlflexibleserver.models.SkuTier;
import com.azure.resourcemanager.postgresqlflexibleserver.models.Storage;
import com.azure.resourcemanager.postgresqlflexibleserver.models.StorageAutoGrow;

public class UpdateServer {
    public static void main(String args[]) {
         String subscriptionId = "<subscription-id>";
         AzureProfile profile = new AzureProfile("<tenant-id>", subscriptionId, AzureEnvironment.AZURE_CHINA);
        
         TokenCredential credential = new DefaultAzureCredentialBuilder()
         .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()).build();
         PostgreSqlManager manager = PostgreSqlManager.authenticate(credential, profile);
         PostgreSqlManager postgreSqlManager = PostgreSqlManager.configure()
         .withLogOptions(new HttpLogOptions()
         .setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
         .authenticate(credential, profile);
         Server resource = manager.servers()
         .getByResourceGroupWithResponse("<resource-group-name>", "<server-name>", com.azure.core.util.Context.NONE)
         .getValue();
         resource.update()
         .withSku(new Sku().withName("Standard_D16ds_v5").withTier(SkuTier.GENERAL_PURPOSE))
         .withAdministratorLoginPassword("<password>")
         .withStorage(new Storage().withStorageSizeGB(1024)
         .withAutoGrow(StorageAutoGrow.DISABLED)
         .withTier(AzureManagedDiskPerformanceTiers.P30))
         .withBackup(new Backup().withBackupRetentionDays(20))
         .withAuthConfig(new AuthConfig().withActiveDirectoryAuth(ActiveDirectoryAuthEnum.ENABLED)
         .withPasswordAuth(PasswordAuthEnum.ENABLED)
         .withTenantId("<tenant-id>"))
         .withCreateMode(CreateModeForUpdate.UPDATE)
         .apply();
         System.out.println("Updated successfully");
 }
}

运行 java 文件,并使用“UpdateServer.java”文件查看资源中所做的更改。

清理资源

通过使用 delete() 方法从 postgresqlflexibleserver 库中删除灵活服务器实例,可以清理创建的灵活服务器实例。

创建一个 DeleteServer.java 文件,并添加以下代码。

package com.example.restservice;

import com.azure.core.credential.TokenCredential;
import com.azure.core.http.policy.HttpLogDetailLevel;
import com.azure.core.http.policy.HttpLogOptions;
import com.azure.core.management.AzureEnvironment;
import com.azure.core.management.profile.AzureProfile;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.resourcemanager.postgresqlflexibleserver.PostgreSqlManager;

public class DeleteInstance {
    public static void main(String args[]) {
          String subscriptionId = "<subscription-id>";
          AzureProfile profile = new AzureProfile("<tenant-id>", subscriptionId, AzureEnvironment.AZURE_CHINA);
         
          TokenCredential credential = new DefaultAzureCredentialBuilder()
          .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()).build();
          PostgreSqlManager manager = PostgreSqlManager.authenticate(credential, profile);
          PostgreSqlManager postgreSqlManager = PostgreSqlManager.configure()
          .withLogOptions(new HttpLogOptions()
          .setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
          .authenticate(credential, profile);
          manager.servers().delete("<resource-group>", "<server-name>", com.azure.core.util.Context.NONE);
          System.out.println("Deleted successfully");
 }

}

将以下参数替换为你自己的数据:

  • subscription-id:你自己的订阅 ID
  • resource-group:要使用的资源组的名称。
  • tenant-id:Microsoft Entra 帐户的租户 ID。 可以从门户或使用 CLI 获取此信息
  • server-name:已创建的 Azure 数据库灵活服务器实例的名称。

还可以删除通过门户、CLI 或 PowerShell 创建的资源组。 如果要使用 CLI 或 PowerShell 将其删除,请按照 CLI 和 PowerShell 部分中提到的步骤进行作。

将占位符替换为你的详细信息,然后运行该文件。

或者,您可以使用以下命令移除资源组:

  • Azure CLI:az group delete --name <resource_group>
  • PowerShell:Remove-AzResourceGroup -Name <resource_group>
  • Azure 门户:导航到资源组并删除它。