共用方式為


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 Topic 觸發程式訂閱主題的 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 Topic 觸發程式。 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 可透過屬性傳送 可透過 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 發佈和訂閱。