共用方式為


Dapr 發佈 Azure Functions 的輸出系結

Dapr 發佈輸出系結可讓您在函式執行期間將訊息發佈至 Dapr 主題。

如需 Dapr 延伸模組的安裝和設定詳細資料,請參閱 Dapr 延伸模組概觀

Example

您可以使用下列其中一種 C# 模式來建立 C# 函式:

Execution model Description
隔離式工作者模型 您的函數程式碼在個別的 .NET 背景工作處理序中執行。 搭配 支援的 .NET 和 .NET Framework 版本使用。 若要深入瞭解,請參閱 隔離背景工作模型中執行 C# Azure Functions 的指南
In-process model 您的函數程式碼執行的處理序與 Functions 主機處理序相同。 僅支援 .NET 的長期支援 (LTS) 版本。 若要深入瞭解,請參閱 使用 Azure Functions 開發 C# 類別庫函式。

下列範例示範如何使用 Dapr 發佈輸出系結,對 pub/sub 元件和主題執行 Dapr 發佈作業。

[FunctionName("PublishOutputBinding")]
public static void Run(
    [HttpTrigger(AuthorizationLevel.Function, "post", Route = "topic/{topicName}")] HttpRequest req,
    [DaprPublish(PubSubName = "%PubSubName%", Topic = "{topicName}")] out DaprPubSubEvent pubSubEvent,
    ILogger log)
{
    string requestBody = new StreamReader(req.Body).ReadToEnd();
    pubSubEvent = new DaprPubSubEvent(requestBody);
}

下列範例會 "TransferEventBetweenTopics" 使用 系 DaprPublishOutput 結搭配 來建立函 DaprTopicTrigger式:

@FunctionName("TransferEventBetweenTopics")
public String run(
        @DaprTopicTrigger(
            pubSubName = "%PubSubName%",
            topic = "A")
            String request,
        @DaprPublishOutput(
            pubSubName = "%PubSubName%",
            topic = "B")
        OutputBinding<String> payload,
        final ExecutionContext context) throws JsonProcessingException {
    context.getLogger().info("Java function processed a TransferEventBetweenTopics request from the Dapr Runtime.");
}

在下列範例中,Dapr 發佈輸出系結會與 對象註冊 app 的 HTTP 觸發程式配對:

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

app.generic('PublishOutputBinding', {
    trigger: trigger.generic({
        type: 'httpTrigger',
        authLevel: 'anonymous',
        methods: ['POST'],
        route: "topic/{topicName}",
        name: "req"
    }),
    return: daprPublishOutput,
    handler: async (request, context) => {
        context.log("Node HTTP trigger function processed a request.");
        const payload = await request.text();
        context.log(JSON.stringify(payload));

        return { payload: 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 daprPublish:

{
  "bindings": 
    {
      "type": "daprPublish",
      "direction": "out",
      "name": "pubEvent",
      "pubsubname": "%PubSubName%",
      "topic": "B"
    }
}

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

# Example to use Dapr Service Invocation Trigger and Dapr State Output binding to persist a new state into statestore
param (
    $subEvent
)

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

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

$messageFromTopicA = "Transfer from Topic A: $jsonString".Trim()

$publish_output_binding_req_body = @{
    "payload" = $messageFromTopicA
}

# Associate values to output bindings by calling 'Push-OutputBinding'.
Push-OutputBinding -Name pubEvent -Value $publish_output_binding_req_body

下列範例示範使用 v2 Python 程式設計模型的 Dapr Publish 輸出系結。 若要在您的 Python 函式應用程式程式碼中使用 daprPublish

import logging
import json
import azure.functions as func

app = func.FunctionApp()

@app.function_name(name="TransferEventBetweenTopics")
@app.dapr_topic_trigger(arg_name="subEvent", pub_sub_name="%PubSubName%", topic="A", route="A")
@app.dapr_publish_output(arg_name="pubEvent", pub_sub_name="%PubSubName%", topic="B")
def main(subEvent, pubEvent: func.Out[bytes]) -> None:
    logging.info('Python function processed a TransferEventBetweenTopics request from the Dapr Runtime.')
    subEvent_json = json.loads(subEvent)
    payload = "Transfer from Topic A: " + str(subEvent_json["data"])
    pubEvent.set(json.dumps({"payload": payload}).encode('utf-8'))

Attributes

In the in-process model, use the DaprPublish to define a Dapr publish output binding, which supports these parameters:

function.json property Description 可透過屬性傳送 可透過 RequestBody 傳送
PubSubName 要傳送訊息的 Dapr pub/sub 名稱。 ✔️ ✔️
Topic 要傳送訊息的 Dapr 主題名稱。 ✔️ ✔️
Payload Required. 正在發佈的訊息。 ✔️

Annotations

DaprPublishOutput 注可讓您讓函式存取已發佈的訊息。

Element Description 可透過屬性傳送 可透過 RequestBody 傳送
pubSubName 要傳送訊息的 Dapr pub/sub 名稱。 ✔️ ✔️
topic 要傳送訊息的 Dapr 主題名稱。 ✔️ ✔️
payload Required. 正在發佈的訊息。 ✔️

Configuration

下表說明您在程式碼中設定的繫結設定屬性。

Property Description 可透過屬性傳送 可透過 RequestBody 傳送
pubsubname 發行者元件服務的名稱。 ✔️ ✔️
topic 發行者主題的名稱/標識符。 ✔️ ✔️
payload Required. 正在發佈的訊息。 ✔️

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

function.json property Description 可透過屬性傳送 可透過 RequestBody 傳送
pubsubname 發行者元件服務的名稱。 ✔️ ✔️
topic 發行者主題的名稱/標識符。 ✔️ ✔️
payload Required. 正在發佈的訊息。 ✔️

下表說明您在 Python 程式碼中設定的 @dapp.dapr_publish_output 繫結組態屬性。

Property Description 可透過屬性傳送 可透過 RequestBody 傳送
pub_sub_name 發行者事件的名稱。 ✔️ ✔️
topic 發行者主題名稱/標識符。 ✔️ ✔️
payload Required. 正在發佈的訊息。 ✔️

如果屬性在 Attributes 和 RequestBody 中都有定義,則系統會優先考量 RequestBody 中提供的資料。

See the Example section for complete examples.

Usage

若要使用 Dapr 發佈輸出系結,請先設定 Dapr pub/sub 元件。 您可以在官方 Dapr 文件中深入了解要使用哪個元件,以及如何進行設定。

若要在 Python v2 中使用 daprPublish,請設定您的專案使其具備正確的相依性。

  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 發佈和訂閱。