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

快速入门:创建 C# Durable Functions 应用

使用 Durable Functions(Azure Functions 功能)在 C# 中编写有状态无服务器工作流。 在本快速入门中,你将克隆并运行一个示例应用,该应用演示了函数链接业务流程协调模式:

  • 函数链式调用:依次调用活动(东京→西雅图→伦敦)。

最后,你将使用 Durable Task Scheduler 模拟器在本地运行业务流程,并能够在仪表板中查看其状态。

  • 克隆并准备 Hello Cities 示例项目。
  • 为本地开发设置持久任务计划程序模拟器和 Azurite。
  • 构建并运行函数应用,然后触发协调流程。
  • 在 Durable Task Scheduler 仪表板中查看编排状态和输出。

先决条件

设置持久任务计划程序模拟器

Durable Task Scheduler 模拟器提供本地开发环境,使你无需 Azure 订阅即可测试协调流程。 .NET Functions 主机还需要Azurite进行本地存储。

启动两个容器:

docker run -d --name dtsemulator -p 8080:8080 -p 8082:8082 \
  mcr.microsoft.com/dts/dts-emulator:latest

docker run -d --name azurite -p 10000:10000 -p 10001:10001 -p 10002:10002 \
  mcr.microsoft.com/azure-storage/azurite

Tip

模拟器启动后,可在 http://localhost:8082 访问 Durable Task Scheduler 仪表板以监控编排。

运行快速入门示例

  1. 导航到 Hello Cities 示例目录:

    cd samples/durable-functions/dotnet/HelloCities/http
    
  2. 创建一个包含模拟器配置的 local.settings.json 文件:

    {
      "IsEncrypted": false,
      "Values": {
        "AzureWebJobsStorage": "UseDevelopmentStorage=true",
        "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
        "DURABLE_TASK_SERVICE_CONNECTION_STRING": "Endpoint=http://localhost:8080;TaskHub=default;Authentication=None",
        "TASKHUB_NAME": "default"
      }
    }
    
  3. 生成项目:

    dotnet build
    
  4. 启动函数应用:

    func start
    
  5. 在单独的终端中,触发编排:

    $response = Invoke-RestMethod -Method POST -Uri http://localhost:7071/api/DurableFunctionsOrchestrationCSharp1_HttpStart
    $response
    

    响应包含业务流程协调实例的状态 URL。 statusQueryGetUri复制该值并运行该值以检查结果:

    Invoke-RestMethod -Uri $response.statusQueryGetUri
    

预期输出

POST 请求返回一个包含状态 URL 的 JSON 响应。 例如:

{
  "id": "<instanceId>",
  "statusQueryGetUri": "http://localhost:7071/runtime/webhooks/durabletask/instances/<instanceId>?code=...",
  "sendEventPostUri": "...",
  "terminatePostUri": "...",
  "purgeHistoryDeleteUri": "..."
}

当你查询 statusQueryGetUri 且编排的 runtimeStatusCompleted 时,可以在 output 字段中找到问候结果:

{
  "name": "DurableFunctionsOrchestrationCSharp1",
  "runtimeStatus": "Completed",
  "output": ["Hello Tokyo!", "Hello Seattle!", "Hello London!"]
}

Tip

如果 runtimeStatus 显示 RunningPending,请稍等片刻,然后再次查询 statusQueryGetUri

打开 Durable Task Scheduler 仪表板 http://localhost:8082 以查看业务流程状态和执行历史记录。

了解代码

DurableFunctionsOrchestrationCSharp1.cs中的示例项目包含Durable Functions应用所需的所有三种函数类型。

活动函数

SayHello 活动接受一个城市名称并返回一条问候语:

[Function(nameof(SayHello))]
public static string SayHello([ActivityTrigger] string name, FunctionContext executionContext)
{
    ILogger logger = executionContext.GetLogger("SayHello");
    logger.LogInformation("Saying hello to {name}.", name);
    return $"Hello {name}!";
}

协调器函数

编排器按顺序针对三个城市调用 SayHello

[Function(nameof(DurableFunctionsOrchestrationCSharp1))]
public static async Task<List<string>> RunOrchestrator(
    [OrchestrationTrigger] TaskOrchestrationContext context)
{
    ILogger logger = context.CreateReplaySafeLogger(nameof(DurableFunctionsOrchestrationCSharp1));
    logger.LogInformation("Saying hello.");
    var outputs = new List<string>();

    outputs.Add(await context.CallActivityAsync<string>(nameof(SayHello), "Tokyo"));
    outputs.Add(await context.CallActivityAsync<string>(nameof(SayHello), "Seattle"));
    outputs.Add(await context.CallActivityAsync<string>(nameof(SayHello), "London"));

    return outputs;
}

客户端函数

由 HTTP 触发的客户端函数启动协调流程:

[Function("DurableFunctionsOrchestrationCSharp1_HttpStart")]
public static async Task<HttpResponseData> HttpStart(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequestData req,
    [DurableClient] DurableTaskClient client,
    FunctionContext executionContext)
{
    ILogger logger = executionContext.GetLogger("DurableFunctionsOrchestrationCSharp1_HttpStart");
    string instanceId = await client.ScheduleNewOrchestrationInstanceAsync(
        nameof(DurableFunctionsOrchestrationCSharp1));

    logger.LogInformation("Started orchestration with ID = '{instanceId}'.", instanceId);
    return await client.CreateCheckStatusResponseAsync(req, instanceId);
}

配置

此示例使用 Durable Task Scheduler 模拟器作为其存储后端。 这将在 host.json 中进行配置:

{
  "version": "2.0",
  "extensions": {
    "durableTask": {
      "storageProvider": {
        "type": "azureManaged",
        "connectionStringName": "DURABLE_TASK_SERVICE_CONNECTION_STRING"
      },
      "hubName": "%TASKHUB_NAME%"
    }
  }
}

模拟器连接字符串和任务中心名称在 local.settings.json 中设置:

{
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
    "DURABLE_TASK_SERVICE_CONNECTION_STRING": "Endpoint=http://localhost:8080;TaskHub=default;Authentication=None",
    "TASKHUB_NAME": "default"
  }
}

清理资源

完成后停止模拟器容器:

docker stop dtsemulator azurite && docker rm dtsemulator azurite

后续步骤