Condividi tramite


Trigger argomento dapr per Funzioni di Azure

Funzioni di Azure può essere attivato in una sottoscrizione dell'argomento Dapr usando gli eventi Dapr seguenti.

Per informazioni sull'installazione e sulla configurazione dell'estensione Dapr, vedere panoramica dell'estensione Dapr.

Example

È possibile creare una funzione C# usando una delle modalità C# seguenti:

Execution model Description
Modello di lavoro isolato Il codice della funzione viene eseguito in un processo di lavoro .NET separato. Usare con le versioni supportate di .NET e .NET Framework. Per altre informazioni, vedere Guida per l'esecuzione di Funzioni di Azure C# nel modello di lavoro isolato.
In-process model Il codice della funzione viene eseguito nello stesso processo del processo host di Funzioni. Supporta solo versioni LTS (Long Term Support) di .NET. Per altre informazioni, vedere Sviluppare funzioni della libreria di classi C# usando Funzioni di Azure.
[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);
}

Ecco il codice Java per la sottoscrizione a un argomento usando il trigger argomento Dapr:

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

Usare l'oggetto app per registrare :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"

L'esempio seguente illustra un trigger argomento dapr, che usa il modello di programmazione Python v2. Per usare nel codice dell'app per le daprTopicTrigger funzioni 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 Nome del pub/sub dapr.
Topic Nome dell'argomento Dapr.

Annotations

L'annotazione DaprTopicTrigger consente di creare una funzione che viene eseguita quando viene ricevuto un argomento.

Element Description
pubSubName Nome del pub/sub dapr.
topic Nome dell'argomento Dapr.

Configuration

Nella tabella seguente vengono illustrate le proprietà di configurazione dell'associazione impostate nel codice.

Property Description
pubsubname Nome del tipo di componente dapr pub/sub.
topic Nome dell'argomento.

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

function.json property Description
pubsubname Nome del tipo di componente dapr pub/sub.
topic Nome dell'argomento.

La tabella seguente illustra le proprietà di configurazione dell'associazione per @dapp.dapr_topic_trigger impostate nel codice Python.

Property Description Può essere inviato tramite Attributo Può essere inviato tramite RequestBody
pub_sub_name Nome del tipo di componente della sottoscrizione Dapr. ✔️
topic Argomento relativo alla sottoscrizione. ✔️

See the Example section for complete examples.

Usage

Per usare un trigger argomento Dapr, iniziare configurando un componente dapr pub/sub. Per altre informazioni sul componente da usare e su come configurarlo, vedere la documentazione ufficiale di Dapr.

Per usare daprTopicTrigger in Python v2, configurare il progetto con le dipendenze corrette.

  1. Creare e attivare un ambiente virtuale.

  2. Nel file requirements.text aggiungere la riga seguente:

    azure-functions==1.18.0b3
    
  3. Nel terminale installare la libreria Python.

    pip install -r .\requirements.txt
    
  4. Modificare il file local.setting.json con la configurazione seguente:

    "PYTHON_ISOLATE_WORKER_DEPENDENCIES":1
    

Next steps

Altre informazioni sulla pubblicazione e la sottoscrizione di Dapr.