你当前正在访问 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("TransferEventBetweenTopics")]
public static void Run(
    [DaprTopicTrigger("%PubSubName%", Topic = "A")] CloudEvent subEvent,
    [DaprPublish(PubSubName = "%PubSubName%", Topic = "B")] out DaprPubSubEvent pubEvent,
    ILogger log)
{
    log.LogInformation("C# function processed a TransferEventBetweenTopics request from the Dapr Runtime.");


    pubEvent = new DaprPubSubEvent("Transfer from Topic A: " + subEvent.Data);
}

下面是使用 Dapr 主题触发器订阅主题的 Java 代码:

@FunctionName("PrintTopicMessage")
public String run(
        @DaprTopicTrigger(
            pubSubName = "%PubSubName%",
            topic = "B")
        String payload,
        final ExecutionContext context) throws JsonProcessingException {
    Logger logger = context.getLogger();
    logger.info("Java function processed a PrintTopicMessage request from the Dapr Runtime.");

使用 app 对象注册 daprTopicTrigger

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

app.generic('TransferEventBetweenTopics', {
    trigger: trigger.generic({
        type: 'daprTopicTrigger',
        name: "subEvent",
        pubsubname: "%PubSubName%",
        topic: "A"
    }),
    return: daprPublishOutput,
    handler: async (request, context) => {
        context.log("Node function processed a TransferEventBetweenTopics request from the Dapr Runtime.");
        context.log(context.triggerMetadata.subEvent.data);

        return { payload: context.triggerMetadata.subEvent.data };
    }
});

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 daprTopicTrigger:

{
  "bindings": [
    {
      "type": "daprTopicTrigger",
      "pubsubname": "%PubSubName%",
      "topic": "B",
      "name": "subEvent",
      "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 (
    $subEvent
)

Write-Host "PowerShell function processed a PrintTopicMessage request from the Dapr Runtime."

# Convert the object to a JSON-formatted string with ConvertTo-Json
$jsonString = $subEvent["data"] | ConvertTo-Json -Compress

Write-Host "Topic B received a message: $jsonString"

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

import logging
import json
import azure.functions as func

app = func.FunctionApp()

@app.function_name(name="PrintTopicMessage")
@app.dapr_topic_trigger(arg_name="subEvent", pub_sub_name="%PubSubName%", topic="B", route="B")
def main(subEvent) -> None:
    logging.info('Python function processed a PrintTopicMessage request from the Dapr Runtime.')
    subEvent_json = json.loads(subEvent)
    logging.info("Topic B received a message: " + subEvent_json["data"])

Attributes

In the in-process model, use the DaprTopicTrigger to trigger a Dapr pub/sub binding, which supports the following properties.

Parameter Description
PubSubName Dapr pub/sub 的名称。
Topic Dapr 主题的名称。

Annotations

DaprTopicTrigger 注允许创建在收到主题时运行的函数。

Element Description
pubSubName Dapr pub/sub 的名称。
topic Dapr 主题的名称。

Configuration

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

Property Description
pubsubname Dapr pub/sub 组件类型的名称。
topic 主题名称。

The following table explains the binding configuration properties that you set in the function.json file.

function.json property Description
pubsubname Dapr pub/sub 组件类型的名称。
topic 主题名称。

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

Property Description 可通过 Attribute 发送 可通过 RequestBody 发送
pub_sub_name Dapr 订阅组件类型的名称。 ✔️
topic 订阅主题。 ✔️

See the Example section for complete examples.

Usage

若要使用 Dapr 主题触发器,请首先设置 Dapr pub/sub 组件。 可在 Dapr 官方文档中详细了解可使用的组件及其设置方式。

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

  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 发布和订阅。