이 빠른 시작에서는 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 계정
- 최신 버전의 JDK(Java Development Kit)
- 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 유연한 서버 인스턴스에 대한 구성 설정을 관리할 수 있습니다.
az cli를 사용하여 계정 설정
Java용 Azure SDK를 사용하여 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);
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 계정의 테넌트 ID입니다. 포털에서 또는 CLI를 사용하여 가져올 수 있습니다. -
resource-group-name: 리소스 그룹의 이름입니다. -
server-name: PostgreSQL 서버의 고유한 이름입니다. -
location: 서버에 대한 Azure 지역입니다. -
admin-username: 관리자 사용자 이름입니다. -
admin-password: 관리자 암호입니다.
Authentication
자격 증명을 인증하는 방법에는 여러 가지가 있습니다. 이 예제에서는 Azure 서비스를 사용하여 인증하는 데 사용할 수 있는 자격 증명인 TokenCredential 개체를 구성하고 만드는 데 사용 DefaultAzureCredentialBuilder 했습니다. 필수 구성 요소에 설명된 대로 Azure CLI를 사용하여 로그인합니다.
파일 실행
maven 프로젝트를 만들고 아래 명령을 실행했는지 확인합니다. 파일에 새 종속성을 추가하여 로컬 리포지토리에 pom.xml 해당 종속성을 설치할 때마다 다음 명령을 실행해야 합니다.
mvn clean install
파일을 실행하려면 IDE를 사용하여 이 코드를 실행하거나 명령줄을 사용하여 Java 파일을 실행할 수 있습니다.
javac <file-name>.java
java <file-name>
비고
이 코드를 실행하면 인스턴스 만들기 프로세스가 시작되며 완료하는 데 몇 분 정도 걸릴 수 있습니다.
Azure Portal, 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);
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: 리소스 그룹으로 이동하여 삭제합니다.