使用 JavaScript 创建你的第一个持久函数Create your first durable function in JavaScript

Durable FunctionsAzure Functions 的一个扩展,可用于在无服务器环境中编写有状态函数。Durable Functions is an extension of Azure Functions that lets you write stateful functions in a serverless environment. 该扩展可用于管理状态、检查点和重启。The extension manages state, checkpoints, and restarts for you.

本文介绍了如何使用 Visual Studio Code Azure Functions 扩展在本地创建并测试“hello world”持久函数。In this article, you learn how to use the Visual Studio Code Azure Functions extension to locally create and test a "hello world" durable function. 此函数将协调对其他函数的调用并将其链接在一起。This function will orchestrate and chain together calls to other functions. 然后将函数代码发布到 Azure。You then publish the function code to Azure.

在 Azure 中运行持久函数

先决条件Prerequisites

完成本教程:To complete this tutorial:

如果没有 Azure 订阅,可在开始前创建一个试用帐户If you don't have an Azure subscription, create a trial account before you begin.

创建本地项目Create your local project

在本部分,你将使用 Visual Studio Code 创建一个本地 Azure Functions 项目。In this section, you use Visual Studio Code to create a local Azure Functions project.

  1. 在 Visual Studio Code 中,按 F1(或 Ctrl/命令键+Shift+P)打开命令面板。In Visual Studio Code, press F1 (or Ctrl/Cmd+Shift+P) to open the command palette. 在命令面板中,搜索并选择 Azure Functions: Create New Project...In the command palette, search for and select Azure Functions: Create New Project....

    创建函数

  2. 为项目选择一个空文件夹位置,然后选择“选择”。Choose an empty folder location for your project and choose Select.

  3. 按照提示提供以下信息:Following the prompts, provide the following information:

    PromptPrompt Value 说明Description
    选择函数应用项目的语言Select a language for your function app project JavascriptJavaScript 创建本地 Node.js Functions 项目。Create a local Node.js Functions project.
    选择版本Select a version Azure Functions v3Azure Functions v3 仅当尚未安装 Core Tools 时,才会出现此选项。You only see this option when the Core Tools aren't already installed. 在本例中,当你首次运行应用时即已安装 Core Tools。In this case, Core Tools are installed the first time you run the app.
    为项目的第一个函数选择模板Select a template for your project's first function 暂时跳过Skip for now
    选择打开项目的方式Select how you would like to open your project 在当前窗口中打开Open in current window 在所选的文件夹中重新打开 VS Code。Reopens VS Code in the folder you selected.

Visual Studio Code 会根据需要安装 Azure Functions Core Tools。Visual Studio Code installs the Azure Functions Core Tools, if needed. 它还会在某个文件夹中创建一个函数应用项目。It also creates a function app project in a folder. 此项目包含 host.jsonlocal.settings.json 配置文件。This project contains the host.json and local.settings.json configuration files.

此外,还会在根文件夹中创建 package.json 文件。A package.json file is also created in the root folder.

安装 Durable Functions npm 包Install the Durable Functions npm package

若要在 Node.js 函数应用中使用 Durable Functions,请使用名为 durable-functions 的库。To work with Durable Functions in a Node.js function app, you use a library called durable-functions.

  1. 使用“视图”菜单或按 Ctrl+Shift+`,在 VS Code 中打开新的终端。Use the View menu or Ctrl+Shift+` to open a new terminal in VS Code.

  2. 通过运行函数应用的根目录中的 npm install durable-functions 来安装 durable-functions npm 包。Install the durable-functions npm package by running npm install durable-functions in the root directory of the function app.

创建函数Creating your functions

最基本的 Durable Functions 应用包含三个函数:The most basic Durable Functions app contains three functions:

  • 业务流程协调程序函数 - 描述用于协调其他函数的工作流。Orchestrator function - describes a workflow that orchestrates other functions.
  • 活动函数 - 由业务流程协调程序函数调用,它会执行工作并选择性地返回一个值。Activity function - called by the orchestrator function, performs work, and optionally returns a value.
  • 客户端函数 - 用于启动业务流程协调程序函数的常规 Azure 函数。Client function - a regular Azure Function that starts an orchestrator function. 本示例使用 HTTP 触发的函数。This example uses an HTTP triggered function.

业务流程协调程序函数Orchestrator function

你将使用一个模板在项目中创建持久函数代码。You use a template to create the durable function code in your project.

  1. 在命令面板中,搜索并选择 Azure Functions: Create Function...In the command palette, search for and select Azure Functions: Create Function....

  2. 按照提示提供以下信息:Following the prompts, provide the following information:

    PromptPrompt Value 说明Description
    选择函数的模板Select a template for your function Durable Functions 业务流程协调程序Durable Functions orchestrator 创建 Durable Functions 业务流程Create a Durable Functions orchestration
    提供函数名称Provide a function name HelloOrchestratorHelloOrchestrator 持久函数的名称Name of your durable function

现已添加一个业务流程协调程序来协调活动函数。You've added an orchestrator to coordinate activity functions. 打开 HelloOrchestrator/index.js 查看业务流程协调程序函数。Open HelloOrchestrator/index.js to see the orchestrator function. 每次调用 context.df.callActivity 都会调用名为 Hello 的活动函数。Each call to context.df.callActivity invokes an activity function named Hello.

接下来,添加引用的 Hello 活动函数。Next, you'll add the referenced Hello activity function.

活动函数Activity function

  1. 在命令面板中,搜索并选择 Azure Functions: Create Function...In the command palette, search for and select Azure Functions: Create Function....

  2. 按照提示提供以下信息:Following the prompts, provide the following information:

    PromptPrompt Value 说明Description
    选择函数的模板Select a template for your function Durable Functions 活动Durable Functions activity 创建活动函数Create an activity function
    提供函数名称Provide a function name 你好Hello 活动函数的名称Name of your activity function

现已添加业务流程协调程序调用的 Hello 活动函数。You've added the Hello activity function that is invoked by the orchestrator. 打开 Hello/index.js,可以看到,该函数采用某个名称作为输入,并返回一句问候语。Open Hello/index.js to see that it's taking a name as input and returning a greeting. 将在活动函数中执行操作,例如,发出数据库调用或执行计算。An activity function is where you'll perform actions such as making a database call or performing a computation.

最后,添加一个启动业务流程的 HTTP 触发的函数。Finally, you'll add an HTTP triggered function that starts the orchestration.

客户端函数(HTTP 启动器)Client function (HTTP starter)

  1. 在命令面板中,搜索并选择 Azure Functions: Create Function...In the command palette, search for and select Azure Functions: Create Function....

  2. 按照提示提供以下信息:Following the prompts, provide the following information:

    PromptPrompt Value 说明Description
    选择函数的模板Select a template for your function Durable Functions HTTP 启动器Durable Functions HTTP starter 创建 HTTP 启动器函数Create an HTTP starter function
    提供函数名称Provide a function name DurableFunctionsHttpStartDurableFunctionsHttpStart 活动函数的名称Name of your activity function
    授权级别Authorization level 匿名Anonymous 出于演示目的,请允许在不进行身份验证的情况下调用函数For demo purposes, allow the function to be called without authentication

现已添加一个启动业务流程的 HTTP 触发的函数。You've added an HTTP triggered function that starts an orchestration. 打开 DurableFunctionsHttpStart/index.js,可以看到,该函数使用 client.startNew 启动新的业务流程。Open DurableFunctionsHttpStart/index.js to see that it uses client.startNew to start a new orchestration. 然后,它使用 client.createCheckStatusResponse 返回 HTTP 响应,其中包含可用于监视和管理新业务流程的 URL。Then it uses client.createCheckStatusResponse to return an HTTP response containing URLs that can be used to monitor and manage the new orchestration.

现已创建一个可在本地运行并可部署到 Azure 的 Durable Functions 应用。You now have a Durable Functions app that can be run locally and deployed to Azure.

在本地测试函数Test the function locally

使用 Azure Functions Core Tools 可以在本地开发计算机上运行 Azure Functions 项目。Azure Functions Core Tools lets you run an Azure Functions project on your local development computer. 首次从 Visual Studio Code 启动某个函数时,系统会提示你安装这些工具。You're prompted to install these tools the first time you start a function from Visual Studio Code.

  1. 若要测试函数,请在 Hello 活动函数代码 (Hello/node.js) 中设置断点。To test your function, set a breakpoint in the Hello activity function code (Hello/index.js). 按 F5 或者在命令面板中选择 Debug: Start Debugging 以启动函数应用项目。Press F5 or select Debug: Start Debugging from the command palette to start the function app project. 来自 Core Tools 的输出会显示在“终端”面板中。Output from Core Tools is displayed in the Terminal panel.

    备注

    有关调试的详细信息,请参阅 Durable Functions 诊断Refer to the Durable Functions Diagnostics for more information on debugging.

  2. Durable Functions 需要一个 Azure 存储帐户才能运行。Durable Functions requires an Azure Storage account to run. 当 VS Code 提示选择存储帐户时,请选择“选择存储帐户”。When VS Code prompts you to select a storage account, choose Select storage account.

    创建存储帐户

  3. 按照提示提供以下信息,以在 Azure 中创建新的存储帐户。Following the prompts, provide the following information to create a new storage account in Azure.

    PromptPrompt Value 说明Description
    选择订阅Select subscription 订阅的名称name of your subscription 选择 Azure 订阅Select your Azure subscription
    选择存储帐户Select a storage account 新建存储帐户Create a new storage account
    输入新存储帐户的名称Enter the name of the new storage account 唯一名称unique name 要创建的存储帐户的名称Name of the storage account to create
    选择资源组Select a resource group 唯一名称unique name 要创建的资源组名称Name of the resource group to create
    选择位置Select a location regionregion 选择离你较近的区域Select a region close to you
  4. 在“终端” 面板中,复制 HTTP 触发的函数的 URL 终结点。In the Terminal panel, copy the URL endpoint of your HTTP-triggered function.

    Azure 本地输出

  5. 使用浏览器或者 PostmancURL 之类的工具向 URL 终结点发送一个 HTTP POST 请求。Using your browser, or a tool like Postman or cURL, send an HTTP POST request to the URL endpoint. 将最后一个段替换为业务流程协调程序函数的名称 (HelloOrchestrator)。Replace the last segment with the name of the orchestrator function (HelloOrchestrator). URL 应类似于 http://localhost:7071/api/orchestrators/HelloOrchestratorThe URL should be similar to http://localhost:7071/api/orchestrators/HelloOrchestrator.

    响应是来自 HTTP 函数的初始结果,告知持久业务流程已成功启动。The response is the initial result from the HTTP function letting you know the durable orchestration has started successfully. 它还不是业务流程的最终结果。It is not yet the end result of the orchestration. 响应中包括了几个有用的 URL。The response includes a few useful URLs. 现在,让我们查询业务流程的状态。For now, let's query the status of the orchestration.

  6. 复制 statusQueryGetUri 的 URL 值,将其粘贴到浏览器的地址栏中并执行请求。Copy the URL value for statusQueryGetUri and paste it in the browser's address bar and execute the request. 或者也可以继续使用 Postman 发出 GET 请求。Alternatively you can also continue to use Postman to issue the GET request.

    请求将查询业务流程实例的状态。The request will query the orchestration instance for the status. 你应该会得到一个最终响应,它显示实例已经完成,并包含持久函数的输出或结果。You should get an eventual response, which shows us the instance has completed, and includes the outputs or results of the durable function. 输出如下所示:It looks like:

    {
        "name": "HelloOrchestrator",
        "instanceId": "9a528a9e926f4b46b7d3deaa134b7e8a",
        "runtimeStatus": "Completed",
        "input": null,
        "customStatus": null,
        "output": [
            "Hello Tokyo!",
            "Hello Seattle!",
            "Hello London!"
        ],
        "createdTime": "2020-03-18T21:54:49Z",
        "lastUpdatedTime": "2020-03-18T21:54:54Z"
    }
    
  7. 若要停止调试,请在 VS Code 中按 Shift + F5To stop debugging, press Shift + F5 in VS Code.

确认该函数可以在本地计算机上正确运行以后,即可将项目发布到 Azure。After you've verified that the function runs correctly on your local computer, it's time to publish the project to Azure.

登录 AzureSign in to Azure

在发布应用之前,必须先登录到 Azure。Before you can publish your app, you must sign in to Azure.

  1. 打开 Visual Studio Code,然后单击 View -> Command Palette...Open Visual Studio Code, click View -> Command Palette....

  2. 输入 Sign In to Azure Cloud,以搜索 Azure 中国环境。Input Sign In to Azure Cloud to search Azure China Environment.

  3. 在搜索结果中单击 Azure ChinaClick Azure China in search result.

  4. 窗口的右下角将出现一个弹出窗口。You will find a popup window at the bottom right of your window.

    弹出窗口

  5. 打开页面 **https://microsoft.com/deviceloginchina**,然后输入该代码进行身份验证。Open the page https://microsoft.com/deviceloginchina and enter the code to authenticate.

将项目发布到 AzurePublish the project to Azure

在本部分,你将在 Azure 订阅中创建一个函数应用和相关资源,然后部署代码。In this section, you create a function app and related resources in your Azure subscription and then deploy your code.

重要

发布到现有函数应用将覆盖该应用在 Azure 中的内容。Publishing to an existing function app overwrites the content of that app in Azure.

  1. 在活动栏中选择“Azure”图标,然后在“Azure:函数”区域中,选择“部署到函数应用...”按钮。Choose the Azure icon in the Activity bar, then in the Azure: Functions area, choose the Deploy to function app... button.

    将项目发布到 Azure

  2. 根据提示提供以下信息:Provide the following information at the prompts:

    • 选择文件夹:从工作区中选择一个文件夹,或浏览到包含函数应用的文件夹。Select folder: Choose a folder from your workspace or browse to one that contains your function app. 如果已打开有效的函数应用,则不会看到此信息。You won't see this if you already have a valid function app opened.

    • 选择订阅:选择要使用的订阅。Select subscription: Choose the subscription to use. 如果只有一个订阅,则不会看到此项。You won't see this if you only have one subscription.

    • 在 Azure 中选择函数应用:选择+ Create new Function AppSelect Function App in Azure: Choose + Create new Function App. (请不要选择本文中未介绍的 Advanced 选项。)(Don't choose the Advanced option, which isn't covered in this article.)

    • 输入函数应用的全局唯一名称:键入在 URL 路径中有效的名称。Enter a globally unique name for the function app: Type a name that is valid in a URL path. 将对你键入的名称进行验证,以确保其在 Azure Functions 中是唯一的。The name you type is validated to make sure that it's unique in Azure Functions.

    • 选择运行时:选择你一直在本地运行的 Node.js 版本。Select a runtime: Choose the version of Node.js you've been running on locally. 可以使用 node --version 命令来检查你的版本。You can use the node --version command to check your version.
    • 选择新资源的位置:为了获得更好的性能,请选择你附近的区域Select a location for new resources: For better performance, choose a region near you.
  3. 完成后,将使用基于函数应用名称的名称在订阅中创建以下 Azure 资源:When completed, the following Azure resources are created in your subscription, using names based on your function app name:

    • 一个资源组:相关资源的逻辑容器。A resource group, which is a logical container for related resources.
    • 一个标准 Azure 存储帐户:用于维护项目的状态和其他信息。A standard Azure Storage account, which maintains state and other information about your projects.
    • 一个消耗计划:用于定义无服务器函数应用的基础主机。A consumption plan, which defines the underlying host for your serverless function app.
    • 一个函数应用:提供用于执行函数代码的环境。A function app, which provides the environment for executing your function code. 可以通过函数应用将函数分组为逻辑单元,以便在同一托管计划中更轻松地管理、部署和共享资源。A function app lets you group functions as a logical unit for easier management, deployment, and sharing of resources within the same hosting plan.

    创建函数应用并应用了部署包之后,会显示一个通知。A notification is displayed after your function app is created and the deployment package is applied.

  4. 在此通知中选择“查看输出”以查看创建和部署结果,其中包括你创建的 Azure 资源。Select View Output in this notification to view the creation and deployment results, including the Azure resources that you created. 如果错过了通知,请选择右下角的响铃图标以再次查看。If you miss the notification, select the bell icon in the lower right corner to see it again.

    创建完成通知

在 Azure 中测试函数Test your function in Azure

  1. 从“输出” 面板复制 HTTP 触发器的 URL。Copy the URL of the HTTP trigger from the Output panel. 调用 HTTP 触发的函数的 URL 应采用此格式:http://<functionappname>.chinacloudsites.cn/api/orchestrators/HelloOrchestratorThe URL that calls your HTTP-triggered function should be in this format: http://<functionappname>.chinacloudsites.cn/api/orchestrators/HelloOrchestrator

  2. 将 HTTP 请求的这个新 URL 粘贴到浏览器的地址栏中。Paste this new URL for the HTTP request into your browser's address bar. 你应当会得到与之前使用已发布的应用时相同的状态响应。You should get the same status response as before when using the published app.

后续步骤Next steps

你已使用 Visual Studio Code 创建并发布了一个 JavaScript 持久函数应用。You have used Visual Studio Code to create and publish a JavaScript durable function app.