このクイック スタートでは、JavaのAzure SDKを使用して、Azure Database for PostgreSQLフレキシブル サーバーを作成、更新、削除する方法について説明します。 コード例は Java で記述され、Azure SDK ライブラリを使用して Azure Database for PostgreSQL サービスと対話します。
JavaのAzure SDKには、Javaを使用してAzure サービスを操作するために使用できる一連のライブラリが用意されています。 SDK は一貫したプログラミング モデルを提供し、Azure Database for PostgreSQL を含む Azure サービスの操作を簡略化します。
前提条件
- アクティブなサブスクリプションが含まれる Azure アカウント
- 最新バージョンの Java Development Kit (JDK)
- Azure Java SDK ライブラリを使用するための Maven のダウンロード
- ローカル コンピューターにインストールされている Azure CLI
Azure Java SDK でサポートされる操作
JavaのAzure SDKは、Azure Databases for PostgreSQL に対するこれらの操作をサポートするazure-resourcemanager-postgresqlflexibleserver依存関係を提供します。
Azure Database for PostgreSQL フレキシブル サーバーの作成
場所、SKU、ストレージ、バージョンなどの構成を指定して、新しい Azure PostgreSQL フレキシブル サーバーを作成できます。Azure Database for PostgreSQL フレキシブル サーバーの更新
管理者のサインイン、パスワード、SKU、ストレージ、バージョンなどの構成の変更など、既存の Azure PostgreSQL フレキシブル サーバーを更新できます。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>
Note
ファイルに追加する前に、すべての依存関係の最新バージョンを確認してください。
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);
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 を使用して認証を行います。 認証されると、指定した構成で postgreSQL フレキシブル サーバー Azureが定義されます。
コード内の次のパラメーターを実際のデータに置き換えます。
-
subscription-id:お使いの Azure サブスクリプション ID。 -
tenant-id: Microsoft Entra アカウントのテナント ID。 これは、ポータルから、または 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 PostgreSQL フレキシブル サーバーは、Azure ポータル、Azure CLI、Azure PowerShell、その他のさまざまなツールを使用して確認し、デプロイを検証し、デプロイされたリソースを確認できます。
データベースの作成
新しく作成したサーバーに新しいデータベースを追加できます。 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);
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 ファイルを使用してリソースに加えられた変更を確認します。
リソースをクリーンアップする
作成されたフレキシブル サーバーをクリーンアップするには、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);
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 portal: リソース グループに移動して削除します。