使用 JAVA 建立第一個耐久函式

Durable FunctionsAzure Functions 的擴充功能,可讓您在無伺服器環境中撰寫具狀態函式。 此擴充功能會為您管理狀態、設定檢查點和重新啟動。

在本快速入門中,您將了解如何使用 JAVA 來建立及測試 "Hello World" Durable Functions 應用程式。 最基本的 Durable Functions 應用程式會包含下列三個函式:

  • 協調器函式 - 描述用於協調其他函式的工作流程。
  • 活動函式 - 由協調器函式呼叫,可執行工作並選擇性地傳回值。
  • 用戶端函式 - 可啟動協調器函式的一般 Azure 函式。 此範例會使用 HTTP 觸發的函式。

本快速入門將示範如何以不同的方式建立這個 "Hello World" 應用程式。 使用上述選取器來選擇您慣用的方法。

必要條件

若要完成本教學課程,您需要:

如果您沒有 Azure 訂用帳戶,請在開始之前先建立 Azure 免費帳戶

將必要的相依性和外掛程式新增至專案

在您的 pom.xml 中新增下列內容:

<properties>
  <azure.functions.maven.plugin.version>1.18.0</azure.functions.maven.plugin.version>
  <azure.functions.java.library.version>3.0.0</azure.functions.java.library.version>
  <durabletask.azure.functions>1.0.0</durabletask.azure.functions>
  <functionAppName>your-unique-app-name</functionAppName>
</properties>

<dependencies>
  <dependency>
    <groupId>com.microsoft.azure.functions</groupId>
    <artifactId>azure-functions-java-library</artifactId>
    <version>${azure.functions.java.library.version}</version>
  </dependency>
  <dependency>
    <groupId>com.microsoft</groupId>
    <artifactId>durabletask-azure-functions</artifactId>
    <version>${durabletask.azure.functions}</version>
  </dependency>
</dependencies>

<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-compiler-plugin</artifactId>
      <version>3.8.1</version>
    </plugin>
    <plugin>
      <groupId>com.microsoft.azure</groupId>
      <artifactId>azure-functions-maven-plugin</artifactId>
      <version>${azure.functions.maven.plugin.version}</version>
      <configuration>
        <appName>${functionAppName}</appName>
        <resourceGroup>java-functions-group</resourceGroup>
        <appServicePlanName>java-functions-app-service-plan</appServicePlanName>
        <region>westus</region>
        <runtime>
          <os>windows</os>
          <javaVersion>11</javaVersion>
        </runtime>
        <appSettings>
          <property>
            <name>FUNCTIONS_EXTENSION_VERSION</name>
            <value>~4</value>
          </property>
        </appSettings>
      </configuration>
      <executions>
        <execution>
          <id>package-functions</id>
          <goals>
            <goal>package</goal>
          </goals>
        </execution>
      </executions>
    </plugin>
    <plugin>
      <artifactId>maven-clean-plugin</artifactId>
      <version>3.1.0</version>
    </plugin>
  </plugins>
</build>

新增必要的 JSON 檔案

host.json 檔案新增至專案目錄。 看起來應類似下列範例:

{
  "version": "2.0",
  "logging": {
    "logLevel": {
      "DurableTask.AzureStorage": "Warning",
      "DurableTask.Core": "Warning"
    }
  },
  "extensions": {
    "durableTask": {
      "hubName": "JavaTestHub"
    }
  },
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[4.*, 5.0.0)"
  }
}

注意

請務必注意,只有 Azure Functions v4 延伸模組套件組合目前針對適用於 Java 的 Durable Functions 提供必要支援。 v3 和早期延伸模組套件組合支援適用於 Java 的 Durable Functions。 如需延伸模組套件組合的詳細資訊,請參閱延伸模組套件組合文件

Durable Functions 需要儲存體提供者來儲存執行階段狀態。 將 local.settings.json 檔案新增至專案目錄,以設定儲存體提供者。 若要使用 Azure 儲存體作為提供者,請將 AzureWebJobsStorage 的值設定為 Azure 儲存體帳戶的連接字串:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "<your storage account connection string>",
    "FUNCTIONS_WORKER_RUNTIME": "java"
  }
}

建立您的函式

下方範例程式碼顯示每個項目的簡單範例:

import com.microsoft.azure.functions.annotation.*;
import com.microsoft.azure.functions.*;
import java.util.*;

import com.microsoft.durabletask.*;
import com.microsoft.durabletask.azurefunctions.DurableActivityTrigger;
import com.microsoft.durabletask.azurefunctions.DurableClientContext;
import com.microsoft.durabletask.azurefunctions.DurableClientInput;
import com.microsoft.durabletask.azurefunctions.DurableOrchestrationTrigger;

public class DurableFunctionsSample {
    /**
     * This HTTP-triggered function starts the orchestration.
     */
    @FunctionName("StartOrchestration")
    public HttpResponseMessage startOrchestration(
            @HttpTrigger(name = "req", methods = {HttpMethod.GET, HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request,
            @DurableClientInput(name = "durableContext") DurableClientContext durableContext,
            final ExecutionContext context) {
        context.getLogger().info("Java HTTP trigger processed a request.");

        DurableTaskClient client = durableContext.getClient();
        String instanceId = client.scheduleNewOrchestrationInstance("Cities");
        context.getLogger().info("Created new Java orchestration with instance ID = " + instanceId);
        return durableContext.createCheckStatusResponse(request, instanceId);
    }

    /**
     * This is the orchestrator function, which can schedule activity functions, create durable timers,
     * or wait for external events in a way that's completely fault-tolerant.
     */
    @FunctionName("Cities")
    public String citiesOrchestrator(
            @DurableOrchestrationTrigger(name = "taskOrchestrationContext") TaskOrchestrationContext ctx) {
        String result = "";
        result += ctx.callActivity("Capitalize", "Tokyo", String.class).await() + ", ";
        result += ctx.callActivity("Capitalize", "London", String.class).await() + ", ";
        result += ctx.callActivity("Capitalize", "Seattle", String.class).await() + ", ";
        result += ctx.callActivity("Capitalize", "Austin", String.class).await();
        return result;
    }

    /**
     * This is the activity function that gets invoked by the orchestrator function.
     */
    @FunctionName("Capitalize")
    public String capitalize(@DurableActivityTrigger(name = "name") String name, final ExecutionContext context) {
        context.getLogger().info("Capitalizing: " + name);
        return name.toUpperCase();
    }
}

使用 Maven 命令建立本機專案

  1. 執行下列命令來產生具有 Durable Functions 應用程式基本函式的專案:
mvn archetype:generate -DarchetypeGroupId=com.microsoft.azure -DarchetypeArtifactId=azure-functions-archetype -DarchetypeVersion=1.51 -Dtrigger=durablefunctions
  1. 依照提示操作並提供下列資訊:
提示
groupId com.function
artifactId myDurableFunction
version 1.0-SNAPSHOT
套件 com.function
Y 點擊 Enter 確認

現在您已使用基本 Durable Functions 應用程式所需的三個函式產生本機專案。

請檢查以確定您的 pom.xml 中有 com.microsoft:durabletask-azure-functions 作為相依性。

設定後端儲存體提供者

Durable Functions 需要儲存體提供者來儲存執行階段狀態。 您可以將您的 Azure 儲存體帳戶連接字串當成值提供給 AzureWebJobsStorage,藉此在 local.settings.json 中設定使用 Azure 儲存體作為儲存體提供者:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "<your storage account connection string>",
    "FUNCTIONS_WORKER_RUNTIME": "java"
  }
}

建立本機專案

  1. 在 Visual Studio Code 中,按 F1 (或 Ctrl/Cmd+Shift+P) 以開啟命令選擇區。 在命令選擇區中,搜尋並選取 Azure Functions: Create New Project...

    Screenshot of create new functions project.

  2. 為您的專案選擇空白資料夾位置,然後選擇 [選取]

  3. 依照提示操作並提供下列資訊:

    提示
    選取語言 選擇 Java
    選取 JAVA 的版本 選擇您的函式在 Azure 中執行的 Java 版本 Java 8 或更新版本。 選擇您已在本機驗證的 Java 版本。
    提供群組識別碼 com.function.
    提供成品識別碼 myDurableFunction.
    提供版本 1.0-SNAPSHOT.
    提供套件名稱 com.function.
    提供應用程式名稱 myDurableFunction.
    選取 JAVA 專案的建置工具 選擇 Maven
    選取您開啟專案的方式 選擇 Open in new window

您現在已擁有含有範例 HTTP 函式的專案。 如果您想要移除此函式,則可逕行移除,因為我們將在下一個步驟中新增 Durable Functions 應用程式的基本函式。

將函式新增至專案

  1. 在命令選擇區中,搜尋並選取 Azure Functions: Create Function...

  2. Change template filter 選擇為 All

  3. 依照提示操作並提供下列資訊:

    提示
    選取函式的範本 DurableFunctionsOrchestration
    提供套件名稱 com.function
    提供函式名稱 DurableFunctionsOrchestrator
  4. 選擇快顯視窗上的 Select storage account,要求設定儲存體帳戶資訊並遵循提示。

現在在產生的 Durable Functions 應用程式中應該有三個基本函式。

設定 pom.xml 和 host.json

將下列相依性新增至 pom.xml

<dependency>
  <groupId>com.microsoft</groupId>
  <artifactId>durabletask-azure-functions</artifactId>
  <version>1.0.0</version>
</dependency>

extensions 屬性新增至您的 host.json

"extensions": { "durableTask": { "hubName": "JavaTestHub" }}

在本機測試函式

Azure Functions Core Tools 可讓您在本機開發電腦上執行 Azure Functions 專案。

注意

適用於 Java 的 Durable Functions 需要 Azure Functions Core Tools v4.0.4915 或更新版本。 您可以從終端機執行 func --version 命令,以查看安裝的版本。

  1. 如果您使用 Visual Studio Code,請開啟新的終端機視窗,然後執行下列命令來建置專案:

    mvn clean package
    

    然後執行耐久函式:

    mvn azure-functions:run
    
  2. 在終端機面板中,複製 HTTP 觸發函式的 URL 端點。

    Screenshot of Azure local output.

  3. 使用 PostmancURL 之類的工具,將 HTTP POST 要求傳送至 URL 端點。 您應該會看到如下所示的回應:

    {
        "id": "d1b33a60-333f-4d6e-9ade-17a7020562a9",
        "purgeHistoryDeleteUri": "http://localhost:7071/runtime/webhooks/durabletask/instances/d1b33a60-333f-4d6e-9ade-17a7020562a9?code=ACCupah_QfGKoFXydcOHH9ffcnYPqjkddSawzRjpp1PQAzFueJ2tDw==",
        "sendEventPostUri": "http://localhost:7071/runtime/webhooks/durabletask/instances/d1b33a60-333f-4d6e-9ade-17a7020562a9/raiseEvent/{eventName}?code=ACCupah_QfGKoFXydcOHH9ffcnYPqjkddSawzRjpp1PQAzFueJ2tDw==",
        "statusQueryGetUri": "http://localhost:7071/runtime/webhooks/durabletask/instances/d1b33a60-333f-4d6e-9ade-17a7020562a9?code=ACCupah_QfGKoFXydcOHH9ffcnYPqjkddSawzRjpp1PQAzFueJ2tDw==",
        "terminatePostUri": "http://localhost:7071/runtime/webhooks/durabletask/instances/d1b33a60-333f-4d6e-9ade-17a7020562a9/terminate?reason={text}&code=ACCupah_QfGKoFXydcOHH9ffcnYPqjkddSawzRjpp1PQAzFueJ2tDw=="
    }
    

    回應是 HTTP 函式的初始結果,讓您知道耐久協調流程已成功啟動。 這還不是協調流程的最終結果。 回應包含一些實用的 URL。 讓現在我們查詢協調流程的狀態。

  4. 複製 statusQueryGetUri 的 URL 值並將它貼在瀏覽器的網址列中,然後執行要求。 或者,您也可以繼續使用 Postman 或 cRUL 來發出 GET 要求。

    此要求會查詢協調流程執行個體的狀態。 您應該會取得最終回應,內容指出執行個體已完成,並包含耐久函式的輸出或結果。 如下所示:

    {
        "name": "Cities",
        "instanceId": "d1b33a60-333f-4d6e-9ade-17a7020562a9",
        "runtimeStatus": "Completed",
        "input": null,
        "customStatus": "",
        "output":"TOKYO, LONDON, SEATTLE, AUSTIN",
        "createdTime": "2022-12-12T05:00:02Z",
        "lastUpdatedTime": "2022-12-12T05:00:06Z"
    }