共用方式為


在 Azure 上使用 Java 開始使用雲端開發

本文將逐步引導您為 Java 中的 Azure 開發設定開發環境。 接著,您將建立一些 Azure 資源並連線到它們,以執行一些基本工作,例如上傳檔案或部署 Web 應用程式。 完成後,您就可以開始在自己的 Java 應用程式中使用 Azure 服務。

先決條件

設定驗證

您的 Java 應用程式需要 讀取,並 在 Azure 訂用帳戶中建立 許可權,才能在本教學課程中執行範例程式代碼。 建立服務主體,並設定您的應用程式以其認證執行。 服務主體提供一種方式,讓您建立與您身分識別相關聯的非互動帳戶,而您只授與應用程式執行所需的許可權。

使用 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 show標識碼 值。
  • AZURE_CLIENT_ID:使用從服務主體輸出擷取的輸出 appId 值。
  • AZURE_CLIENT_SECRET:使用服務主體輸出中的 密碼 值。
  • AZURE_TENANT_ID:使用服務主體輸出中的 租使用者 值。

如需更多驗證選項,請參閱適用於 Java 的 azure 身分識別用戶端連結庫

注意

Microsoft建議使用最安全的驗證流程。 此程式中所述的驗證流程,例如資料庫、快取、傳訊或 AI 服務,在應用程式中需要高度的信任,而且不會在其他流程中帶來風險。 只有在更安全的選項,例如無密碼或無密鑰連線的受控識別時,才能使用此流程。 針對本機計算機作業,偏好使用無密碼或無密鑰連線的使用者身分識別。

工具

建立新的 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 的新檔案,並貼上下列程式代碼區塊。 使用您機器的實際值更新 userNamesshKey 變數。 此程式代碼會建立新的 Linux 虛擬機(VM),其名稱 testLinuxVM 於資源群組中 sampleResourceGroup 在美國東部 Azure 區域中執行。

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 對 Azure REST API 進行基礎呼叫以設定 VM 及其資源時,您會在控制台中看到一些 REST 要求和回應。 程式完成之後,請使用 Azure CLI 2.0 確認訂用帳戶中的 VM。

az vm list --resource-group sampleVmResourceGroup

驗證程式代碼是否正常運作之後,請使用 CLI 來刪除 VM 及其資源。

az group delete --name sampleVmResourceGroup

從 GitHub 存放庫部署 Web 應用程式

App.java 中的main方法取代為下列方法。 在執行程式代碼之前,請先將 appName 變數更新為唯一值。 此程式代碼會將公用 GitHub 存放庫中的 master 分支中的 Web 應用程式部署到免費定價層中執行的新 Azure App Service Web 應用程式

    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

驗證部署之後,請從您的訂用帳戶移除 Web 應用程式和方案。

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 記憶體帳戶。 然後程式代碼會使用適用於 Java 的 Azure 記憶體連結庫,在雲端中建立新的文本檔。

    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 入口網站,或使用 Azure 記憶體總管,瀏覽記憶體帳戶中的 helloazure.txt 檔案。

使用 CLI 清除記憶體帳戶。

az group delete --name sampleStorageResourceGroup

探索更多範例

若要深入瞭解如何使用適用於 Java 的 Azure 管理連結庫來管理資源和自動化工作,請參閱我們的範例程式代碼,虛擬機Web 應用程式,以及 SQL 資料庫

參考和版本資訊

參考 適用於所有套件。

取得說明並提供意見反應

在 Stack Overflow 上張貼問題給社群。 在 GitHub 存放庫中,針對適用於 Java 的 Azure SDK 回報 Bug 和開啟問題,