다음을 통해 공유


Azure에서 Java를 사용하여 클라우드 개발 시작

이 문서에서는 Java에서 Azure 개발을 위한 개발 환경을 설정하는 방법을 안내합니다. 그런 다음, 일부 Azure 리소스를 만들고 연결하여 파일 업로드 또는 웹 애플리케이션 배포와 같은 몇 가지 기본 작업을 수행합니다. 완료되면 사용자 고유의 Java 애플리케이션에서 Azure 서비스를 사용할 준비가 됩니다.

필수 구성 요소

인증 설정

Java 애플리케이션은 읽기 읽고 이 자습서의 샘플 코드를 실행하기 위해 Azure 구독에서 권한을 만들 있어야 합니다. 서비스 주체를 만들고 해당 자격 증명을 사용하여 실행되도록 애플리케이션을 구성합니다. 서비스 주체는 앱이 실행하는 데 필요한 권한만 부여하는 ID와 연결된 비대화형 계정을 만드는 방법을 제공합니다.

Azure CLI 2.0사용하여 서비스 주체를 만들고 출력을 캡처합니다.

az ad sp create-for-rbac \
    --name AzureJavaTest \
    --role Contributor \
    --scopes /subscriptions/<your-subscription-ID>

이 명령은 다음과 같은 형식의 회신을 제공합니다.

{
  "appId": "a487e0c1-82af-47d9-9a0b-af184eb87646d",
  "displayName": "AzureJavaTest",
  "name": "http://AzureJavaTest",
  "password": "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",
  "tenant": "tttttttt-tttt-tttt-tttt-tttttttttttt"
}

다음으로, 환경 변수를 구성합니다.

  • AZURE_SUBSCRIPTION_ID: Azure CLI 2.0의 az account showID 값을 사용합니다.
  • AZURE_CLIENT_ID: 서비스 주체 출력에서 가져온 출력의 appId 값을 사용합니다.
  • AZURE_CLIENT_SECRET: 서비스 주체 출력의 암호 값을 사용합니다.
  • AZURE_TENANT_ID: 서비스 주체 출력의 테넌트 값을 사용합니다.

자세한 인증 옵션은 Java 대한Azure Identity 클라이언트 라이브러리를 참조하세요.

메모

Microsoft는 사용 가능한 가장 안전한 인증 흐름을 사용하는 것이 좋습니다. 데이터베이스, 캐시, 메시징 또는 AI 서비스와 같이 이 절차에서 설명하는 인증 흐름은 애플리케이션에 대한 신뢰 수준이 매우 높고 다른 흐름에 존재하지 않는 위험을 수반합니다. 암호 없는 연결 또는 키 없는 연결에 대한 관리 ID와 같은 더 안전한 옵션이 실행 가능하지 않은 경우에만 이 흐름을 사용합니다. 로컬 컴퓨터 작업의 경우 암호 없는 연결이나 키 없는 연결에 사용자 ID를 사용하는 것이 좋습니다.

압형

새 Maven 프로젝트 만들기

메모

이 문서에서는 Maven 빌드 도구를 사용하여 샘플 코드를 빌드하고 실행합니다. Gradle과 같은 다른 빌드 도구도 Java용 Azure SDK와 함께 작동합니다.

시스템의 새 디렉터리에 있는 명령줄에서 Maven 프로젝트를 만듭니다.

mkdir java-azure-test
cd java-azure-test
mvn archetype:generate -DgroupId=com.fabrikam -DartifactId=AzureApp \
-DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

이 단계에서는 testAzureApp 디렉터리 아래에 기본 Maven 프로젝트를 만듭니다. 프로젝트의 pom.xml 파일에 다음 항목을 추가하여 이 자습서의 샘플 코드에 사용되는 라이브러리를 가져옵니다.

<dependency>
  <groupId>com.azure</groupId>
  <artifactId>azure-identity</artifactId>
  <version>1.3.2</version>
</dependency>
<dependency>
  <groupId>com.azure.resourcemanager</groupId>
  <artifactId>azure-resourcemanager</artifactId>
  <version>2.6.0</version>
</dependency>
<dependency>
  <groupId>com.azure</groupId>
  <artifactId>azure-storage-blob</artifactId>
  <version>12.8.0</version>
</dependency>
<dependency>
  <groupId>com.microsoft.sqlserver</groupId>
  <artifactId>mssql-jdbc</artifactId>
  <version>6.2.1.jre8</version>
</dependency>
<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-simple</artifactId>
  <version>1.7.33</version>
</dependency>

최상위 project 요소 아래에 build 항목을 추가하여 maven-exec-plugin 사용하여 샘플을 실행합니다. maven-compiler-plugin 사용하여 Java 8에 대한 소스 코드 및 생성된 클래스를 구성합니다.

<build>
  <plugins>
    <plugin>
      <groupId>org.codehaus.mojo</groupId>
      <artifactId>exec-maven-plugin</artifactId>
      <version>3.0.0</version>
      <configuration>
        <mainClass>com.fabrikam.App</mainClass>
      </configuration>
    </plugin>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-compiler-plugin</artifactId>
      <version>3.8.1</version>
      <configuration>
        <source>1.8</source>
        <target>1.8</target>
      </configuration>
    </plugin>
  </plugins>
</build>

Linux 가상 머신 만들기

프로젝트의 src/main/java/com/fabrikam 디렉터리에 App.java 새 파일을 만들고 다음 코드 블록에 붙여넣습니다. userName 업데이트하고 sshKey 변수를 컴퓨터에 대한 실제 값으로 업데이트합니다. 이 코드는 미국 동부 Azure 지역에서 실행되는 리소스 그룹 sampleResourceGroup 이름 testLinuxVM 사용하여 새 Linux VM(가상 머신)을 만듭니다.

package com.fabrikam;

import com.azure.core.credential.TokenCredential;
import com.azure.core.http.policy.HttpLogDetailLevel;
import com.azure.core.management.AzureEnvironment;
import com.azure.core.management.Region;
import com.azure.core.management.profile.AzureProfile;
import com.azure.identity.AzureAuthorityHosts;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.resourcemanager.AzureResourceManager;
import com.azure.resourcemanager.compute.models.KnownLinuxVirtualMachineImage;
import com.azure.resourcemanager.compute.models.VirtualMachine;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;

public class App {

    public static void main(String[] args) {

        final String userName = "YOUR_VM_USERNAME";
        final String sshKey = "YOUR_PUBLIC_SSH_KEY";

        try {
            TokenCredential credential = new DefaultAzureCredentialBuilder()
                    .authorityHost(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD)
                    .build();

            // If you don't set the tenant ID and subscription ID via environment variables,
            // change to create the Azure profile with tenantId, subscriptionId, and Azure environment.
            AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE);

            AzureResourceManager azureResourceManager = AzureResourceManager.configure()
                    .withLogLevel(HttpLogDetailLevel.BASIC)
                    .authenticate(credential, profile)
                    .withDefaultSubscription();

            // Create an Ubuntu virtual machine in a new resource group.
            VirtualMachine linuxVM = azureResourceManager.virtualMachines().define("testLinuxVM")
                    .withRegion(Region.US_EAST)
                    .withNewResourceGroup("sampleVmResourceGroup")
                    .withNewPrimaryNetwork("10.0.0.0/24")
                    .withPrimaryPrivateIPAddressDynamic()
                    .withoutPrimaryPublicIPAddress()
                    .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS)
                    .withRootUsername(userName)
                    .withSsh(sshKey)
                    .withSize(VirtualMachineSizeTypes.STANDARD_D3_V2)
                    .create();

        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
}

명령줄에서 샘플을 실행합니다.

mvn compile exec:java

SDK가 VM 및 해당 리소스를 구성하기 위해 Azure REST API에 대한 기본 호출을 수행할 때 콘솔에 일부 REST 요청 및 응답이 표시됩니다. 프로그램이 완료되면 Azure CLI 2.0을 사용하여 구독의 VM을 확인합니다.

az vm list --resource-group sampleVmResourceGroup

코드가 작동하는지 확인한 후 CLI를 사용하여 VM 및 해당 리소스를 삭제합니다.

az group delete --name sampleVmResourceGroup

GitHub 리포지토리에서 웹앱 배포

App.java main 메서드를 다음 메서드로 바꿉다. 코드를 실행하기 전에 appName 변수를 고유한 값으로 업데이트합니다. 이 코드는 공용 GitHub 리포지토리의 master 분기에서 무료 가격 책정 계층에서 실행되는 새 Azure App Service Web App 웹 애플리케이션을 배포합니다.

    public static void main(String[] args) {
        try {

            final String appName = "YOUR_APP_NAME";

            TokenCredential credential = new DefaultAzureCredentialBuilder()
                    .authorityHost(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD)
                    .build();

            // If you don't set the tenant ID and subscription ID via environment variables,
            // change to create the Azure profile with tenantId, subscriptionId, and Azure environment.
            AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE);
            
            AzureResourceManager azureResourceManager = AzureResourceManager.configure()
                    .withLogLevel(HttpLogDetailLevel.BASIC)
                    .authenticate(credential, profile)
                    .withDefaultSubscription();

            WebApp app = azureResourceManager.webApps().define(appName)
                    .withRegion(Region.US_WEST2)
                    .withNewResourceGroup("sampleWebResourceGroup")
                    .withNewWindowsPlan(PricingTier.FREE_F1)
                    .defineSourceControl()
                    .withPublicGitRepository(
                            "https://github.com/Azure-Samples/app-service-web-java-get-started")
                    .withBranch("master")
                    .attach()
                    .create();

        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }

Maven을 사용하기 전과 같이 코드를 실행합니다.

mvn clean compile exec:java

CLI를 사용하여 애플리케이션을 가리키는 브라우저를 엽니다.

az webapp browse --resource-group sampleWebResourceGroup --name YOUR_APP_NAME

배포를 확인한 후 웹앱을 제거하고 구독에서 계획을 수립합니다.

az group delete --name sampleWebResourceGroup

Azure SQL 데이터베이스에 연결

App.java 현재 main 메서드를 다음 코드로 바꿉다. 변수에 대한 실제 값을 설정합니다. 이 코드는 원격 액세스를 허용하는 방화벽 규칙을 사용하여 새 SQL 데이터베이스를 만듭니다. 그런 다음, 코드는 SQL Database JBDC 드라이버를 사용하여 연결합니다.

    public static void main(String args[]) {
        // Create the db using the management libraries.
        try {
            TokenCredential credential = new DefaultAzureCredentialBuilder()
                    .authorityHost(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD)
                    .build();

            // If you don't set the tenant ID and subscription ID via environment variables,
            // change to create the Azure profile with tenantId, subscriptionId, and Azure environment.
            AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE);

            AzureResourceManager azureResourceManager = AzureResourceManager.configure()
                    .withLogLevel(HttpLogDetailLevel.BASIC)
                    .authenticate(credential, profile)
                    .withDefaultSubscription();

            final String adminUser = "YOUR_USERNAME_HERE";
            final String sqlServerName = "YOUR_SERVER_NAME_HERE";
            final String sqlDbName = "YOUR_DB_NAME_HERE";
            final String dbPassword = "YOUR_PASSWORD_HERE";
            final String firewallRuleName = "YOUR_RULE_NAME_HERE";

            SqlServer sampleSQLServer = azureResourceManager.sqlServers().define(sqlServerName)
                    .withRegion(Region.US_EAST)
                    .withNewResourceGroup("sampleSqlResourceGroup")
                    .withAdministratorLogin(adminUser)
                    .withAdministratorPassword(dbPassword)
                    .defineFirewallRule(firewallRuleName)
                        .withIpAddressRange("0.0.0.0","255.255.255.255")
                        .attach()
                    .create();

            SqlDatabase sampleSQLDb = sampleSQLServer.databases().define(sqlDbName).create();

            // Assemble the connection string to the database.
            final String domain = sampleSQLServer.fullyQualifiedDomainName();
            String url = "jdbc:sqlserver://"+ domain + ":1433;" +
                    "database=" + sqlDbName +";" +
                    "user=" + adminUser+ "@" + sqlServerName + ";" +
                    "password=" + dbPassword + ";" +
                    "encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;";

            // Connect to the database, create a table, and insert an entry into it.
            try (Connection conn = DriverManager.getConnection(url)) {
                String createTable = "CREATE TABLE CLOUD (name varchar(255), code int);";
                String insertValues = "INSERT INTO CLOUD (name, code) VALUES ('Azure', 1);";
                String selectValues = "SELECT * FROM CLOUD";
                try (Statement createStatement = conn.createStatement()) {
                    createStatement.execute(createTable);
                }
                try (Statement insertStatement = conn.createStatement()) {
                    insertStatement.execute(insertValues);
                }
                try (Statement selectStatement = conn.createStatement();
                     ResultSet rst = selectStatement.executeQuery(selectValues)) {
                    while (rst.next()) {
                        System.out.println(rst.getString(1) + " " + rst.getString(2));
                    }
                }
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            System.out.println(e.getStackTrace().toString());
        }
    }

명령줄에서 샘플을 실행합니다.

mvn clean compile exec:java

그런 다음 CLI를 사용하여 리소스를 정리합니다.

az group delete --name sampleSqlResourceGroup

새 스토리지 계정에 Blob 쓰기

App.java 현재 main 메서드를 다음 코드로 바꿉다. 이 코드는 Azure Storage 계정만듭니다. 그런 다음, 코드는 Java용 Azure Storage 라이브러리를 사용하여 클라우드에 새 텍스트 파일을 만듭니다.

    public static void main(String[] args) {

        try {
            TokenCredential tokenCredential = new DefaultAzureCredentialBuilder()
                    .authorityHost(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD)
                    .build();

            // If you don't set the tenant ID and subscription ID via environment variables,
            // change to create the Azure profile with tenantId, subscriptionId, and Azure environment.
            AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE);

            AzureResourceManager azureResourceManager = AzureResourceManager.configure()
                    .withLogLevel(HttpLogDetailLevel.BASIC)
                    .authenticate(tokenCredential, profile)
                    .withDefaultSubscription();

            // Create a new storage account.
            String storageAccountName = "YOUR_STORAGE_ACCOUNT_NAME_HERE";
            StorageAccount storage = azureResourceManager.storageAccounts().define(storageAccountName)
                    .withRegion(Region.US_WEST2)
                    .withNewResourceGroup("sampleStorageResourceGroup")
                    .create();

            // Create a storage container to hold the file.
            List<StorageAccountKey> keys = storage.getKeys();
            PublicEndpoints endpoints = storage.endPoints();
            String accountName = storage.name();
            String accountKey = keys.get(0).value();
            String endpoint = endpoints.primary().blob();

            StorageSharedKeyCredential credential = new StorageSharedKeyCredential(accountName, accountKey);

            BlobServiceClient storageClient = new BlobServiceClientBuilder()
                    .endpoint(endpoint)
                    .credential(credential)
                    .buildClient();

            // Container name must be lowercase.
            BlobContainerClient blobContainerClient = storageClient.getBlobContainerClient("helloazure");
            blobContainerClient.create();

            // Make the container public.
            blobContainerClient.setAccessPolicy(PublicAccessType.CONTAINER, null);

            // Write a blob to the container.
            String fileName = "helloazure.txt";
            String textNew = "Hello Azure";

            BlobClient blobClient = blobContainerClient.getBlobClient(fileName);
            InputStream is = new ByteArrayInputStream(textNew.getBytes());
            blobClient.upload(is, textNew.length());

        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }

명령줄에서 샘플을 실행합니다.

mvn clean compile exec:java

Azure Portal 또는 Azure Storage Explorer사용하여 스토리지 계정에서 helloazure.txt 파일을 찾아볼 수 있습니다.

CLI를 사용하여 스토리지 계정을 정리합니다.

az group delete --name sampleStorageResourceGroup

더 많은 샘플 살펴보기

Java용 Azure 관리 라이브러리를 사용하여 리소스를 관리하고 작업을 자동화하는 방법에 대한 자세한 내용은 가상 머신, 웹앱및 SQL 데이터베이스 대한 샘플 코드를 참조하세요.

참조 및 릴리스 정보

참조 모든 패키지에 사용할 수 있습니다.

도움말 보기 및 피드백 제공

Stack Overflow커뮤니티에 질문을 게시합니다. GitHub 리포지토리Java용 Azure SDK에 대한 버그를 보고하고 문제를 엽니다.