共用方式為


在 Azure Stack Hub 中使用 API 版本設定檔搭配 Java

重要

Java SDK 已從追蹤 1 更新為追蹤 2。 建議您儘快移轉至追蹤 2 SDK。 如需指示,請參閱 此移轉指南

適用於 Azure Stack Hub Resource Manager 的 Java SDK 會提供工具,以協助您建置及管理您的基礎結構。 SDK 中的資源提供者包括計算、網路、儲存體、應用程式服務和 Azure Key Vault。 您可以在 GitHub 上找到混合式 JAVA 範例存放庫。 本文將協助您設定環境、取得正確認證、抓取儲存機制,以及在 Azure Stack Hub 中建立資源群組。

使用 Java SDK 可使真正的混合式雲端開發人員體驗發揮功能。 在 Java SDK 中切換 POM.xml 的 版本相依性,可協助您在全域 Azure 資源和 Azure Stack Hub 的資源來回切換,藉此提供混合式雲端開發功能。

若要使用所有服務的最新版本,請將最新設定檔當作相依性使用。

您可以使用現有的 com.azure.resourcemanager 相依性,並將版本從 x.y.z 變更為 x.y.z-hybrid,以將應用程式目標設定為 Azure Stack Hub 中的資源。 混合式套件 (可提供 Azure Stack Hub 的支援) 使用版本結尾的 -hybrid 尾碼,例如 1.0.0-hybrid。 這會指向與此版本相關聯端點的靜態集合。

若要取得最新的設定檔,請採用您現有的 com.azure.resourcemanager 相依性,並將版本變更為最新版本。 最新設定檔 JAVA 套件可提供一致的 Azure 體驗。 這些套件與 Azure com.azure.resourcemanager 共用相同的群組識別碼。 成品識別碼和命名空間也與全域 Azure 相同。 這有助於將您的 Azure 應用程式移植至 Azure Stack Hub。 若要深入瞭解 Azure Stack Hub 中作為混合式設定檔一部分所使用的端點,請參閱 API 設定檔的摘要

設定檔會在 Maven 專案中的 pom.xml 檔案中指定為相依性。 如果您從下拉式清單中選擇正確的類別,則設定檔會自動載入模組 (與使用 .NET 一樣)。

設定開發環境

若要準備執行 SDK 的環境,您可以使用 Eclipse 或 Visual Studio Code 之類的 IDE,但您必須安裝 Git、Java SDK 和 Apache Maven。 您可以在使用 Azure SDK for Java 時,找到設定開發環境必要條件的詳細資料

  1. 安裝 GIT。 您可以在使用者入門 - 安裝 Git 找到安裝 Git 的官方指示。

  2. 安裝 JAVA SDK,並將您的 JAVA_HOME 環境變數設定為 JAVA 開發工具組的二進位檔位置。 您可以找到適用於 OpenJDK 的可下載安裝媒體指示。 安裝第 8 版或更高版本的 JAVA 開發人員套件。

  3. 安裝 Apache Maven。 您可以在 Apache Maven Project 找到指示。 安裝 Apache Maven 為 3.0 或更新版本。

Java 和 API 版本設定檔

若要使用所有服務的最新版本,請將最新設定檔當作相依性使用。

  • 若要使用最新的設定檔,相依性為 com.microsoft.azure

  • 若要使用 Azure Stack Hub 中最新支援的服務,請使用 com.microsoft.azure.profile_2019_03_01_hybrid 設定檔。

    • 此設定檔會在 Pom.xml 檔案中指定為相依性,並在您從下拉式清單中選擇正確類別時 (與使用 .NET 時一樣) 自動載入模組。
  • 相依性如下所示:

    <dependency>
    <groupId>com.microsoft.azure.profile_2019_03_01_hybrid</groupId>
    <artifactId>azure</artifactId>
    <version>1.0.0-beta-1</version>
    </dependency>
    
  • 若要使用特定資源提供者中某個資源類型的特定 API 版本,請使用透過 Intellisense 所定義的特定 API 版本。

您可以在相同應用程式中組合所有選項。

安裝 Azure Java SDK

請依照下列步驟安裝 Java SDK:

  1. 依照官方指示安裝 Git。 請參閱使用者入門 - 安裝 Git

  2. 請依照指示安裝 Java SDKMaven。 Java Developer Kit 的正確版本是第 8 版。 Apache Maven 的正確版本是 3.0 版或更新版本。 若要完成快速入門,JAVA_HOME 環境變數必須設定為 Java 開發套件的安裝位置。 如需詳細資訊,請參閱使用 Java 和 Maven 建立您的第一個函式

  3. 若要安裝正確的相依性套件,請在您的 Java 應用程式中開啟 Pom.xml 檔案。 新增相依性,如下列程式碼所示:

    <dependency>
    <groupId>com.microsoft.azure.profile_2019_03_01_hybrid</groupId>
    <artifactId>azure</artifactId>
    <version>1.0.0-beta-1</version>
    </dependency>
    
  4. 需要安裝的套件集合取決於您想要使用的設定檔版本。 設定檔版本的套件名稱是:

    • com.microsoft.azure.profile_2019_03_01_hybrid
    • com.microsoft.azure
      • 最新

Profiles

針對包含日期的設定檔,若要使用不同的 SDK 設定檔或版本,請以 com.microsoft.azure.profile<date>_hybrid 格式取代日期。 例如,在 2008 版本中,設定檔為 2019_03_01,而該字串則會變成 com.microsoft.azure.profile_2019_03_01_hybrid。 請注意,有時候 SDK 小組會變更套件的名稱,因此僅將字串的日期取代為不同日期,可能無法正確運作。 請參閱下表以了解設定檔與 Azure Stack 版本的關聯。

Azure Stack 版本 設定檔
2311 2020_09_01
2301 2020_09_01
2206 2020_09_01
2108 2020_09_01
2102 2020_09_01
2008 2019_03_01

如需有關 Azure Stack Hub 和 API 設定檔的詳細資訊,請參閱 API 設定檔的摘要

訂用帳戶

如果您還沒有訂用帳戶,請建立訂用帳戶,並儲存訂用帳戶識別碼以供稍後使用。 如需有關如何建立訂閱的詳細資訊,請參閱此文件

服務主體

您應建立服務主體及其相關聯的環境資訊,並將其儲存。 建議使用 owner 角色的服務主體,但視範例而定,contributor 角色可能已足夠。 如需必要值,請參閱範例存放庫中的讀我檔案。 您可以使用 SDK 語言所支援的任何格式讀取這些值,例如透過 JSON 檔案 (即我們的範例所使用的檔案)。 視正在執行的範例而定,並非這些所有值皆可以使用。 如需更新的範例程式碼或進一步資訊,請參閱範例存放庫

租用戶識別碼

若要尋找 Azure Stack Hub 的目錄或租用戶識別碼,請遵循這篇文章的指示。

註冊資源提供者

遵循此文件來註冊所需的資源提供者。 根據要執行的範例而定會需要這些資源提供者。 例如如果您想要執行 VM 範例,則需要註冊 Microsoft.Compute 資源提供者。

Azure Stack Resource Manager 端點

Azure Resource Manager (ARM) 是可讓系統管理員進行部署、管理及監視 Azure 資源的管理架構。 Azure Resource Manager 能夠以群組方式處理這些工作,而非個別單獨作業的方式。 您可以從 Resource Manager 端點取得中繼資料資訊。 此端點會傳回 JSON 檔案,以及執行程式碼所需的資訊。

  • Azure Stack 開發套件 (ASDK) 中的 ResourceManagerEndpointUrl 為:https://management.local.azurestack.external/
  • 整合系統中的 ResourceManagerEndpointUrl 為:https://management.region.<fqdn>/,而 <fqdn> 為您的完整網域名稱。
  • 若要擷取中繼資料,必須要有:<ResourceManagerUrl>/metadata/endpoints?api-version=1.0。 如需可用的 API 版本,請參閱 Azure REST API 規格。 例如,在 2020-09-01 設定檔版本中,您可以將資源提供者 microsoft.resourcesapi-version 變更為 2019-10-01

範例 JSON:

{
   "galleryEndpoint": "https://portal.local.azurestack.external:30015/",
   "graphEndpoint": "https://graph.windows.net/",
   "portal Endpoint": "https://portal.local.azurestack.external/",
   "authentication": 
      {
         "loginEndpoint": "https://login.windows.net/",
         "audiences": ["https://management.yourtenant.onmicrosoft.com/3cc5febd-e4b7-4a85-a2ed-1d730e2f5928"]
      }
}

信任 Azure Stack Hub CA 根憑證

如果您使用 Azure Stack 開發套件 (ASDK),必須信任遠端電腦上的 CA 根憑證。 您不需要信任具有 Azure Stack Hub 整合式系統的 CA 根憑證。

Windows

  1. 將 Azure Stack Hub 的自我簽署憑證匯出至您的桌面。

  2. 在命令提示字元中,將目錄切換至 %JAVA_HOME%\bin

  3. 執行以下命令:

    .\keytool.exe -importcert -noprompt -file <location of the exported certificate here> -alias root -keystore %JAVA_HOME%\lib\security\cacerts -trustcacerts -storepass changeit
    

現有的 API 設定檔

  • com.microsoft.azure.profile_2019_03_01_hybrid:為 Azure Stack Hub 建置的最新設定檔。 只要您是在 1904 或更新版本上,使用此設定檔就能讓服務與 Azure Stack Hub 有最高的相容性。

  • com.microsoft.azure.profile_2018_03_01_hybrid:為 Azure Stack Hub 建置的設定檔。 使用此設定檔就能讓服務與 1808 版或更新版本的 Azure Stack Hub 相容。

  • com.microsoft.azure:包含所有服務最新版本的設定檔。 使用所有服務的最新版本。

如需有關 Azure Stack Hub 和 API 設定檔的詳細資訊,請參閱 API 設定檔的摘要

Azure Java SDK API 設定檔使用方式

下列程式碼會在 Azure Stack Hub 上驗證服務主體。 它會使用租用戶識別碼和驗證基底 (專屬於 Azure Stack Hub) 來建立權杖:

AzureTokenCredentials credentials = new ApplicationTokenCredentials(client, tenant, key, AZURE_STACK)
                    .withDefaultSubscriptionID(subscriptionID);
Azure azureStack = Azure.configure()
                    .withLogLevel(com.microsoft.rest.LogLevel.BASIC)
                    .authenticate(credentials, credentials.defaultSubscriptionID());

這程式碼可讓您使用 API 設定檔相依性,將應用程式成功地部署至 Azure Stack Hub。

定義 Azure Stack Hub 環境設定功能

若要在正確端點上註冊 Azure Stack Hub 雲端,請使用下列程式碼:

// Get Azure Stack Hub cloud endpoints
final HashMap<String, String> settings = getActiveDirectorySettings(armEndpoint);

AzureEnvironment AZURE_STACK = new AzureEnvironment(new HashMap<String, String>() {
                {
                    put("managementEndpointUrl", settings.get("audience"));
                    put("resourceManagerEndpointUrl", armEndpoint);
                    put("galleryEndpointUrl", settings.get("galleryEndpoint"));
                    put("activeDirectoryEndpointUrl", settings.get("login_endpoint"));
                    put("activeDirectoryResourceID", settings.get("audience"));
                    put("activeDirectoryGraphResourceID", settings.get("graphEndpoint"));
                    put("storageEndpointSuffix", armEndpoint.substring(armEndpoint.indexOf('.')));
                    put("keyVaultDnsSuffix", ".vault" + armEndpoint.substring(armEndpoint.indexOf('.')));
                }
            });

上述程式碼中的 getActiveDirectorySettings 呼叫會從中繼資料端點中擷取端點。 它會從發出的呼叫中指出環境變數:

public static HashMap<String, String> getActiveDirectorySettings(String armEndpoint) {

    HashMap<String, String> adSettings = new HashMap<String, String>();
    try {

        // create HTTP Client
        HttpClient httpClient = HttpClientBuilder.create().build();

        // Create new getRequest with below mentioned URL
        HttpGet getRequest = new HttpGet(String.format("%s/metadata/endpoints?api-version=1.0",
                             armEndpoint));

        // Add additional header to getRequest which accepts application/xml data
        getRequest.addHeader("accept", "application/xml");

        // Execute request and catch response
        HttpResponse response = httpClient.execute(getRequest);

        // Check for HTTP response code: 200 = success
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }

        String responseStr = EntityUtils.toString(response.getEntity());
        JSONObject responseJson = new JSONObject(responseStr);
        adSettings.put("galleryEndpoint", responseJson.getString("galleryEndpoint"));
        JSONObject authentication = (JSONObject) responseJson.get("authentication");
        String audience = authentication.get("audiences").toString().split("\"")[1];
        adSettings.put("login_endpoint", authentication.getString("loginEndpoint"));
        adSettings.put("audience", audience);
        adSettings.put("graphEndpoint", responseJson.getString("graphEndpoint"));

    } catch (ClientProtocolException cpe) {
        cpe.printStackTrace();
        throw new RuntimeException(cpe);
    } catch (IOException ioe) {
        ioe.printStackTrace();
        throw new RuntimeException(ioe);
    }
    return adSettings;
}

單元測試專案範例

  1. 使用下列命令來複製存放庫:

    git clone https://github.com/Azure-Samples/Hybrid-Java-Samples.git -b resourcegroup-2019-03-01-hybrid
    
  2. 建立 Azure 服務主體並指派用以存取訂用帳戶的角色。 如需建立服務主體的指示,請參閱使用 Azure PowerShell 建立具有憑證的服務主體

  3. 擷取下列必要的環境變數:

    • AZURE_TENANT_ID
    • AZURE_CLIENT_ID
    • AZURE_CLIENT_SECRET
    • AZURE_SUBSCRIPTION_ID
    • ARM_ENDPOINT
    • RESOURCE_LOCATION
  4. 在使用命令提示字元所建立的服務主體中,以從中擷取的資訊設定下列環境變數:

    • export AZURE_TENANT_ID={your tenant ID}
    • export AZURE_CLIENT_ID={your client ID}
    • export AZURE_CLIENT_SECRET={your client secret}
    • export AZURE_SUBSCRIPTION_ID={your subscription ID}
    • export ARM_ENDPOINT={your Azure Stack Hub Resource Manager URL}
    • export RESOURCE_LOCATION={location of Azure Stack Hub}

    在 Windows 上,請使用 set 而非 export

  5. 使用 getActiveDirectorySettings 函式來擷取 Azure Resource Manager 中繼資料端點。

    // Get Azure Stack Hub cloud endpoints
    final HashMap<String, String> settings = getActiveDirectorySettings(armEndpoint);
    
  6. 在 Pom.xml 檔案中,新增下列相依性以使用 Azure Stack Hub 的 2019-03-01-hybrid 設定檔。 此相依性會安裝與此設定檔相關聯的計算、網路、儲存體、KeyVault 和應用程式服務資源提供者適用模組:

    <dependency>
      <groupId>com.microsoft.azure.profile_2019_03_01_hybrid</groupId>
      <artifactId>azure</artifactId>
      <version>1.0.0-beta-1</version>
    </dependency>
    
  7. 在為設定環境變數而開啟的命令提示字元中,輸入下列命令:

    mvn clean compile exec:java
    

範例

請參閱 此範例存放庫 ,以取得更新到最新的 (追蹤 2) 範例程式代碼。 如需追蹤 1 範例程式代碼,請參閱 此範例存放庫 。 根 README.md 描述一般需求,以及各子目錄均包含的特定範例,其專屬的 README.md 說明如何執行該範例。

如需適用於 Azure Stack 版本 2008 或設定檔 2019-03-01 以及下列範例的詳細資訊,請參閱此處

後續步驟

深入了解 API 設定檔: