你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

使用 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 扩展捆绑包具有对 Durable Functions for Java 的必要支持。 v3 和早期扩展捆绑包不支持 Durable Functions for Java。 有关扩展捆绑包的详细信息,请参阅扩展捆绑包文档

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. 按照提示提供以下信息:
Prompt
groupId com.function
artifactId myDurableFunction
version 1.0-SNAPSHOT
package com.function
按 Enter 确认

现在,你已生成一个本地项目,其中包含基本 Durable Functions 应用所需的三个函数。

请检查以确保在 pom.xml 中将 com.microsoft:durabletask-azure-functions 作为依赖项。

配置后端存储提供程序

Durable Functions 需要存储提供程序来存储运行时状态。 可以配置以在 local.settings.json 中使用 Azure 存储作为存储提供程序,方法是将 Azure 存储帐户的连接字符串作为 AzureWebJobsStorage 的值:

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

创建本地项目

  1. 在 Visual Studio Code 中,按 F1(或 Ctrl/命令键+Shift+P)打开命令面板。 在命令面板中,搜索并选择 Azure Functions: Create New Project...

    Screenshot of create new functions project.

  2. 为项目选择一个空文件夹位置,然后选择“选择”。

  3. 按照提示提供以下信息:

    Prompt
    选择一种语言 选择 Java
    选择一个 Java 版本 选择在 Azure 中运行函数的 Java 版本 Java 8 或更高版本。 选择已在本地验证的 Java 版本。
    提供一个组 ID com.function
    提供一个项目 ID 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. 按照提示提供以下信息:

    Prompt
    选择函数的模板 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 项目。

注意

Durable Functions for Java 需要 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 之类的工具向 URL 终结点发送一个 HTTP POST 请求。 获得的响应应该类似于以下内容:

    {
        "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 或 cURL 发出 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"
    }