使用 Java Azure SDK创建Azure Database for PostgreSQL灵活服务器

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

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

Prerequisites

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 灵活服务器的配置设置,包括检索和更新参数。

使用 Azure CLI 设置帐户

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

使用 Azure 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 = 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 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:管理员密码。

Authentication

可以通过不同的方式对凭据进行身份验证。 在此示例中,用于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

您还可以使用此 Java SDK,并调用 update() 库中的 postgresqlflexibleserver 方法来更新服务器数据。

通过使用此方法 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 帐户的租户标识。 可以从门户或使用 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 门户:导航到资源组并删除它。