利用 Azure Functions 的功能 Durable Functions,在無伺服器環境中撰寫具狀態的函式。 Durable Functions 管理應用程式中的狀態、檢查點和重啟。
在這個快速入門中,你會用 Java 建立並測試一款 Durable Functions 應用程式。
一個基本的 Durable Functions 應用程式有三個功能:
-
Orchestrator 功能 (
Cities):協調其他功能的工作流程。 -
活動函數 (
Capitalize):編排器呼叫以執行工作並回傳值的函式。 -
用戶端函式(Client function ):
StartOrchestration一個由 HTTP 觸發的函式,啟動編排器。
這個快速入門提供三種設定路徑。 請使用頁面頂端的選擇器選擇您偏好的做法:
- 手動設定:手動建立每個檔案,以完全掌控專案結構。
- Maven 指令:使用 Maven 原型,將專案架構成一個指令。
- Visual Studio Code:使用 VS Code Azure Functions 擴充功能透過導引式介面產生專案。
先決條件
若要完成本快速入門,您需要:
已安裝 Java Developer Kit 第 8 版或更新版本。
已安裝 Apache Maven 3.0 版或更新版本。
最新版的 Azure Functions Core Tools。
針對 Azure Functions 4.x,需要 Core Tools 4.0.4915 版或更新版本。
HTTP 測試工具,可保護您的數據安全。 如需詳細資訊,請參閱 HTTP 測試工具。
Visual Studio Code,並安裝了 Azure Functions擴充功能(僅用於 Visual Studio Code 設定路徑)。
Azure 訂用帳戶。 要使用 Durable Functions,您必須擁有 Azure 儲存體 帳號。
如果您沒有 Azure 帳戶,請在開始之前建立 免費帳戶 。
將必要的相依性和外掛程式新增至專案
請將以下程式碼加入你的 pom.xml 檔案。 在複製之前,先用一個全局唯一的功能應用程式名稱來取代 your-unique-app-name 。 調整 region、 javaVersion、並 resourceGroup 配合你的環境。
<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)"
}
}
備註
Durable Functions for Java 需要擴充套件 v4。 早期的組合包不被支援。 欲了解更多資訊,請參閱 擴充套件文件。
Durable Functions 需要儲存體提供者來儲存執行階段狀態。 將 local.settings.json 檔案新增至專案目錄,以設定儲存體提供者。 若要使用 Azure 儲存體作為提供者,請將 AzureWebJobsStorage 的值設定為 Azure 儲存體帳戶的連接字串:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "<your storage account connection string>",
"FUNCTIONS_WORKER_RUNTIME": "java"
}
}
Important
local.settings.json 檔案可以包含秘密。 記得把它加到你的 .gitignore 檔案裡,避免把它提交到原始碼控制。
建立你的 Durable Functions 協調器、活動與客戶端功能
下列範例程式碼顯示每種函式類型的基本範例:
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 is 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 指令建立本地 Durable Functions 專案
執行下列命令來產生包含 Durable Functions 應用程式基本函式的專案:
mvn archetype:generate -DarchetypeGroupId=com.microsoft.azure -DarchetypeArtifactId=azure-functions-archetype -DarchetypeVersion=1.62 -Dtrigger=durablefunctions
依照提示提供下列資訊:
| 提示 | Action |
|---|---|
| groupId | 輸入 com.function。 |
| artifactId | 輸入 myDurableFunction。 |
| version | 選取 1.0-SNAPSHOT。 |
| 套件 | 輸入 com.function。 |
| Y | 輸入 Y,然後選取 Enter 以確認。 |
現在,您有一個本機專案,其中具有基本 Durable Functions 應用程式中的三個函式。 模組範本會自動在你的 pom.xml 檔案中包含 com.microsoft:durabletask-azure-functions 作為相依關係。
為 Durable Functions 配置後端儲存提供者
Durable Functions 需要儲存體提供者來儲存執行階段狀態。 您可以將 Azure 儲存體設定為 local.settings.json 中的儲存體提供者。 使用 Azure 儲存體帳戶的連接字串做為 AzureWebJobsStorage 值,如下列範例所示:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "<your storage account connection string>",
"FUNCTIONS_WORKER_RUNTIME": "java"
}
}
Important
local.settings.json 檔案可以包含秘密。 記得把它加到你的 .gitignore 檔案裡,避免把它提交到原始碼控制。
建立本機專案
在 Visual Studio Code 中,選擇 F1(或選擇 Ctrl/Cmd+Shift+P)以開啟指令面板。 在提示(
>)時,輸入並選擇 Azure Functions:建立新專案。
選擇 瀏覽。 在 [選取資料夾] 對話框中,移至要用於您專案的資料夾,然後選擇 [選取]。
依照提示提供下列資訊:
提示 Action 選取語言 選取 Java。 選擇 Java 的版本 選擇 Java 8 或更新版本。 選取函式在 Azure 中執行的 Java 版本,以及您在本機驗證的 Java 版本。 提供群組識別碼 輸入 com.function。 提供成品識別碼 輸入 myDurableFunction。 提供版本 輸入 1.0-SNAPSHOT。 提供套件名稱 輸入 com.function。 提供應用程式名稱 輸入 myDurableFunction。 選擇Java專案的建置工具 選取Maven。 選取您希望專案的開啟方式 選擇 在新視窗中開啟。
您現在有一個具有範例 HTTP 函式的專案。 你可以移除產生的 HTTP 函式,因為你在下一步會新增 Durable Functions。
將函式新增至專案
在指令面板中,進入並選擇 Azure Functions: Create Function。
針對 變更範本篩選,選取 全部。
依照提示提供下列資訊:
提示 Action 選取函式的範本 選取 DurableFunctionsOrchestration。 提供套件名稱 輸入 com.function。 提供函式名稱 輸入 DurableFunctionsOrchestrator。 在對話方塊中,選擇 [選取儲存體帳戶] 來設定儲存體帳戶,然後遵循提示進行。
您現在應該已經擁有為 Durable Functions 應用程式產生的三個基本函式。
設定 pom.xml 和 host.json 以設定 Durable Functions
將下列相依性新增至 pom.xml 檔案:
<dependency>
<groupId>com.microsoft</groupId>
<artifactId>durabletask-azure-functions</artifactId>
<version>1.0.0</version>
</dependency>
將 extensions 屬性新增到您的 host.json 檔案。 如果檔案已有其他屬性,請將該 extensions 區塊合併到現有的 JSON:
{
"version": "2.0",
"extensions": {
"durableTask": {
"hubName": "JavaTestHub"
}
},
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.*, 5.0.0)"
}
}
在本機測試函式
Azure Functions Core Tools 讓你能在本地開發電腦上執行 Azure Functions 專案。
如果您使用 Visual Studio Code,請開啟新的終端機視窗,然後執行下列命令來建置專案:
mvn clean package然後,執行持續性函數:
mvn azure-functions:run在終端機面板中,複製 HTTP 觸發函式的 URL 端點。
終端機輸出截圖,顯示本地Azure Functions執行時的 HTTP 端點 URL。 使用你的 HTTP 測試工具 向 URL 端點發送 HTTP POST 請求。
回應看起來應該類似下列範例:
{ "id": "d1b33a60-333f-4d6e-9ade-17a7020562a9", "purgeHistoryDeleteUri": "http://localhost:7071/runtime/webhooks/durabletask/instances/d1b33a60-333f-4d6e-9ade-17a7020562a9?code=ACCupah_QfGKo...", "sendEventPostUri": "http://localhost:7071/runtime/webhooks/durabletask/instances/d1b33a60-333f-4d6e-9ade-17a7020562a9/raiseEvent/{eventName}?code=ACCupah_QfGKo...", "statusQueryGetUri": "http://localhost:7071/runtime/webhooks/durabletask/instances/d1b33a60-333f-4d6e-9ade-17a7020562a9?code=ACCupah_QfGKo...", "terminatePostUri": "http://localhost:7071/runtime/webhooks/durabletask/instances/d1b33a60-333f-4d6e-9ade-17a7020562a9/terminate?reason={text}&code=ACCupah_QfGKo..." }回應是 HTTP 函式的初始結果。 其可讓您知道長期協調流程已成功啟動。 其尚未顯示協調流程的最終結果。 回應包含一些實用的 URL。 現在,請查詢協調流程的狀態。
複製
statusQueryGetUri的 URL 值,並將其貼在瀏覽器的網址列中,然後執行要求。 或者,您也可以繼續使用 HTTP 測試工具來發出 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" }