使用 Azure SDK for Java 建立 適用於 PostgreSQL 的 Azure 資料庫 靈活伺服器

在這個快速入門中,你將學習如何利用Azure SDK for Java來建立、更新和刪除一個適用於 PostgreSQL 的 Azure 資料庫靈活的伺服器。 程式碼範例是以 Java 撰寫,並使用 Azure SDK 程式庫與適用於 PostgreSQL 的 Azure 資料庫服務互動。

Azure SDK for Java 提供了一組函式庫,讓你能透過 Java 與 Azure 服務互動。 SDK 提供一致的程式設計模型,並簡化 Azure 服務的使用,包括適用於 PostgreSQL 的 Azure 資料庫。

先決條件

Azure Java SDK 支援的作業

適用於 Java 的 Azure SDK 提供可支援適用於 PostgreSQL 的 Azure 資料庫的這些作業的 azure-resourcemanager-postgresqlflexibleserver 相依性。

  • 建立 適用於 PostgreSQL 的 Azure 資料庫 彈性伺服器
    你可以建立一台新的 Azure PostgreSQL 彈性伺服器,並設定指定配置,如位置、SKU、儲存空間和版本。

  • 更新適用於 PostgreSQL 的 Azure 資料庫彈性伺服器
    你可以更新現有的 Azure PostgreSQL 彈性伺服器,包括更改管理員登入、密碼、SKU、儲存空間和版本等設定。

  • 刪除適用於 PostgreSQL 的 Azure 資料庫彈性伺服器

  • 擷取適用於 PostgreSQL 的 Azure 資料庫資訊
    您可以取得現有 Azure PostgreSQL 彈性伺服器的詳細資訊,包括其配置、狀態及其他元資料。

  • 管理資料庫
    你可以在 Azure PostgreSQL 彈性伺服器中建立、更新、刪除及檢索資料庫。

  • 管理防火牆規則
    您可以建立、更新、刪除和擷取執行個體的防火牆規則,以控制存取權。

  • 管理組態設定
    你可以管理 Azure PostgreSQL 彈性伺服器的設定,包括擷取和更新參數。

請使用 Azure CLI 設定你的帳戶

在使用 Azure SDK for Java 建立、更新或刪除 適用於 PostgreSQL 的 Azure 資料庫 靈活伺服器之前,請先使用 Azure CLI 登入你的 Azure 帳號。

請使用 Azure CLI 登入您的帳號。

az login

請先取得您帳戶的租用戶識別碼,因為後面章節中的程式碼會需要用到它。

az account show --query tenantId --output tsv

建立專案

在慣用的 IDE 中建立新的 Maven 專案,並新增適用於 PostgreSQL 的 Azure 資料庫程式庫的相依性。

當你建立 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>

Note

於將相依性新增至你的檔案之前,請先檢查每個相依性的最新版本。

建立「適用於 PostgreSQL 的 Azure 資料庫」執行個體

要建立 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);

              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 類別建立適用於PostgreSQL的 Azure 資料庫彈性實例伺服器。 在呼叫建立方法之前,會先使用 TokenCredential 和 AzureProfile 進行認證。 認證後,它會依照你指定的配置定義 Azure PostgreSQL 彈性伺服器。

以您的資料取代程式碼中的下列參數:

  • subscription-id = 您的 Azure 訂用帳戶識別碼。
  • 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>

Note

執行此程式碼會起始執行個體建立流程,該流程可能需要幾分鐘的時間才能完成。

你可以透過 Azure 入口網站、Azure CLI、Azure PowerShell 及其他各種工具來驗證部署並檢視已部署的 Azure PostgreSQL 彈性伺服器。

建立資料庫

您可以將新的資料庫新增至新建立的伺服器。 請確保你的 適用於 PostgreSQL 的 Azure 資料庫 彈性伺服器正在運行。

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);

        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);

         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檔案檢視資源中所做的變更。

清理資源

你可以使用 postgresqlflexibleserver 函式庫中的 delete() 方法刪除彈性伺服器,藉此清理已建立的彈性伺服器。

建立 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);

          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:您自己的訂用帳戶識別碼。
  • 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 入口網站:瀏覽至資源群組並加以刪除。