Cuir in eagar

Comhroinn trí


Dapr Publish output binding for Azure Functions

The Dapr publish output binding allows you to publish a message to a Dapr topic during a function execution.

For information on setup and configuration details of the Dapr extension, see the Dapr extension overview.

Example

A C# function can be created using one of the following C# modes:

Execution model Description
Isolated worker model Your function code runs in a separate .NET worker process. Use with supported versions of .NET and .NET Framework. To learn more, see Develop .NET isolated worker process functions.
In-process model Your function code runs in the same process as the Functions host process. Supports only Long Term Support (LTS) versions of .NET. To learn more, see Develop .NET class library functions.

The following example demonstrates using a Dapr publish output binding to perform a Dapr publish operation to a pub/sub component and topic.

[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);
}

The following example creates a "TransferEventBetweenTopics" function using the DaprPublishOutput binding with an 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.");
}

In the following example, the Dapr publish output binding is paired with an HTTP trigger, which is registered by the app object:

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

The following example shows a Dapr Publish output binding, which uses the v2 Python programming model. To use daprPublish in your Python function app code:

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 Can be sent via Attribute Can be sent via RequestBody
PubSubName The name of the Dapr pub/sub to send the message. ✔️ ✔️
Topic The name of the Dapr topic to send the message. ✔️ ✔️
Payload Required. The message being published. ✔️

Annotations

The DaprPublishOutput annotation allows you to have a function access a published message.

Element Description Can be sent via Attribute Can be sent via RequestBody
pubSubName The name of the Dapr pub/sub to send the message. ✔️ ✔️
topic The name of the Dapr topic to send the message. ✔️ ✔️
payload Required. The message being published. ✔️

Configuration

The following table explains the binding configuration properties that you set in the code.

Property Description Can be sent via Attribute Can be sent via RequestBody
pubsubname The name of the publisher component service. ✔️ ✔️
topic The name/identifier of the publisher topic. ✔️ ✔️
payload Required. The message being published. ✔️

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

function.json property Description Can be sent via Attribute Can be sent via RequestBody
pubsubname The name of the publisher component service. ✔️ ✔️
topic The name/identifier of the publisher topic. ✔️ ✔️
payload Required. The message being published. ✔️

The following table explains the binding configuration properties for @dapp.dapr_publish_output that you set in your Python code.

Property Description Can be sent via Attribute Can be sent via RequestBody
pub_sub_name The name of the publisher event. ✔️ ✔️
topic The publisher topic name/identifier. ✔️ ✔️
payload Required. The message being published. ✔️

If properties are defined in both Attributes and RequestBody, priority is given to data provided in RequestBody.

See the Example section for complete examples.

Usage

To use the Dapr publish output binding, start by setting up a Dapr pub/sub component. You can learn more about which component to use and how to set it up in the official Dapr documentation.

To use the daprPublish in Python v2, set up your project with the correct dependencies.

  1. Create and activate a virtual environment.

  2. In your requirements.text file, add the following line:

    azure-functions==1.18.0b3
    
  3. In the terminal, install the Python library.

    pip install -r .\requirements.txt
    
  4. Modify your local.setting.json file with the following configuration:

    "PYTHON_ISOLATE_WORKER_DEPENDENCIES":1
    

Next steps

Learn more about Dapr publish and subscribe.