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

Azure Functions 的 Dapr 服务调用触发器

可以使用以下 Dapr 事件在 Dapr 服务调用上触发 Azure Functions。

若要了解 Dapr 扩展的设置和配置详细信息,请参阅 Dapr 扩展概述

Example

可以使用以下 C# 模式之一创建 C# 函数:

Execution model Description
独立工作模型 函数代码在单独的 .NET 工作进程中运行。 与 支持的 .NET 和 .NET Framework 版本一起使用。 若要了解详细信息,请参阅 独立辅助角色模型中运行 C# Azure Functions 的指南
In-process model 函数代码与 Functions 宿主进程在同一进程中运行。 仅支持 .NET 的长期支持 (LTS) 版本。 若要了解详细信息,请参阅 使用 Azure Functions 开发 C# 类库函数
[FunctionName("CreateNewOrder")]
public static void Run(
    [DaprServiceInvocationTrigger] JObject payload,
    [DaprState("%StateStoreName%", Key = "order")] out JToken order,
    ILogger log)
{
    log.LogInformation("C# function processed a CreateNewOrder request from the Dapr Runtime.");

    // payload must be of the format { "data": { "value": "some value" } }
    order = payload["data"];
}

下面是 Dapr 服务调用触发器的 Java 代码:

@FunctionName("CreateNewOrder")
public String run(
        @DaprServiceInvocationTrigger(
            methodName = "CreateNewOrder") 
)

使用 app 对象注册 daprInvokeOutput

const { app, trigger } = require('@azure/functions');

app.generic('InvokeOutputBinding', {
    trigger: trigger.generic({
        type: 'httpTrigger',
        authLevel: 'anonymous',
        methods: ['POST'],
        route: "invoke/{appId}/{methodName}",
        name: "req"
    }),
    return: daprInvokeOutput,
    handler: async (request, context) => {
        context.log("Node HTTP trigger function processed a request.");

        const payload = await request.text();
        context.log(JSON.stringify(payload));

        return { body: payload };
    }
});

The following examples show Dapr triggers in a function.json file and PowerShell code that uses those bindings.

Here's the function.json file for daprServiceInvocationTrigger:

{
  "bindings": [
    {
      "type": "daprServiceInvocationTrigger",
      "name": "payload",
      "direction": "in"
    }
  ]
}

For more information about function.json file properties, see the Configuration section.

In code:

using namespace System
using namespace Microsoft.Azure.WebJobs
using namespace Microsoft.Extensions.Logging
using namespace Microsoft.Azure.WebJobs.Extensions.Dapr
using namespace Newtonsoft.Json.Linq

param (
    $payload
)

# C# function processed a CreateNewOrder request from the Dapr Runtime.
Write-Host "PowerShell function processed a CreateNewOrder request from the Dapr Runtime."

# Payload must be of the format { "data": { "value": "some value" } }

# Convert the object to a JSON-formatted string with ConvertTo-Json
$jsonString = $payload| ConvertTo-Json

# Associate values to output bindings by calling 'Push-OutputBinding'.
Push-OutputBinding -Name order -Value $payload["data"]

以下示例演示使用 v2 Python 编程模型的 Dapr 服务调用触发器。 若要在 daprServiceInvocationTrigger Python 函数应用代码中使用,请执行以下作:

import logging
import json
import azure.functions as func

app = func.FunctionApp()

@app.function_name(name="RetrieveOrder")
@app.dapr_service_invocation_trigger(arg_name="payload", method_name="RetrieveOrder")
@app.dapr_state_input(arg_name="data", state_store="statestore", key="order")
def main(payload, data: str) :
    # Function should be invoked with this command: dapr invoke --app-id functionapp --method RetrieveOrder  --data '{}'
    logging.info('Python function processed a RetrieveOrder request from the Dapr Runtime.')
    logging.info(data)

Attributes

In the in-process model, use the DaprServiceInvocationTrigger to trigger a Dapr service invocation binding, which supports the following properties.

Parameter Description
MethodName Optional. Dapr 调用方应使用的方法的名称。 如果未指定,函数的名称将用作方法名称。

Annotations

通过 DaprServiceInvocationTrigger 批注,可以创建由 Dapr 运行时调用的函数。

Element Description
methodName 方法名称。

Configuration

下表说明了在代码中设置的绑定配置属性。

Property Description
type 必须设置为 daprServiceInvocationTrigger
name 代表函数代码中 Dapr 数据的变量的名称。

下表解释了在 function.json 文件中设置的绑定配置属性。

function.json property Description
type 必须设置为 daprServiceInvocationTrigger
name 代表函数代码中 Dapr 数据的变量的名称。

下表介绍了在 Python 代码中设置的 @dapp.dapr_service_invocation_trigger 的绑定配置属性。

Property Description
method_name 表示 Dapr 数据的变量的名称。

See the Example section for complete examples.

Usage

若要使用 Dapr 服务调用触发器,请详细了解要与服务调用触发器一起使用的组件以及如何在官方 Dapr 文档中设置它们。

要在 Python v2 中使用 daprServiceInvocationTrigger,请使用正确的依赖项设置项目。

  1. 创建并激活虚拟环境

  2. requirements.text 文件中添加以下行:

    azure-functions==1.18.0b3
    
  3. 在终端中安装 Python 库。

    pip install -r .\requirements.txt
    
  4. 使用以下配置修改 local.setting.json 文件:

    "PYTHON_ISOLATE_WORKER_DEPENDENCIES":1
    

Next steps

详细了解 Dapr 服务调用。