Rediger

Share via


Dapr Topic trigger for Azure Functions

Important

The Dapr Extension for Azure Functions is currently in preview and only supported in Azure Container Apps environments.

Azure Functions can be triggered on a Dapr topic subscription using the following Dapr events.

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

Here's the Java code for subscribing to a topic using the Dapr Topic trigger:

@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.");

Use the app object to register the 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"

The following example shows a Dapr Topic trigger, which uses the v2 Python programming model. To use the daprTopicTrigger in your Python function app code:

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 The name of the Dapr pub/sub.
Topic The name of the Dapr topic.

Annotations

The DaprTopicTrigger annotation allows you to create a function that runs when a topic is received.

Element Description
pubSubName The name of the Dapr pub/sub.
topic The name of the Dapr topic.

Configuration

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

Property Description
pubsubname The name of the Dapr pub/sub component type.
topic Name of the topic.

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

function.json property Description
pubsubname The name of the Dapr pub/sub component type.
topic Name of the topic.

The following table explains the binding configuration properties for @dapp.dapr_topic_trigger 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 Dapr subscription component type. ✔️
topic The subscription topic. ✔️

See the Example section for complete examples.

Usage

To use a Dapr Topic trigger, 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 daprTopicTrigger 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.