Rediger

Del via


Azure Event Hubs trigger for Azure Functions

This article explains how to work with Azure Event Hubs trigger for Azure Functions. Azure Functions supports trigger and output bindings for Event Hubs.

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

Use the function trigger to respond to an event sent to an event hub event stream. You must have read access to the underlying event hub to set up the trigger. When the function is triggered, the message passed to the function is typed as a string.

Event Hubs scaling decisions for the Consumption and Premium plans are done via Target Based Scaling. For more information, see Target Based Scaling.

For information about how Azure Functions responds to events sent to an event hub event stream using triggers, see Integrate Event Hubs with serverless functions on Azure.

Important

This article uses tabs to support multiple versions of the Node.js programming model. The v4 model is generally available and is designed to have a more flexible and intuitive experience for JavaScript and TypeScript developers. For more details about how the v4 model works, refer to the Azure Functions Node.js developer guide. To learn more about the differences between v3 and v4, refer to the migration guide.

Azure Functions supports two programming models for Python. The way that you define your bindings depends on your chosen programming model.

The Python v2 programming model lets you define bindings using decorators directly in your Python function code. For more information, see the Python developer guide.

This article supports both programming models.

Example

The following example shows a C# function that is triggered based on an event hub, where the input message string is written to the logs:

{
    private readonly ILogger<EventHubsFunction> _logger;

    public EventHubsFunction(ILogger<EventHubsFunction> logger)
    {
        _logger = logger;
    }

    [Function(nameof(EventHubFunction))]
    [FixedDelayRetry(5, "00:00:10")]
    [EventHubOutput("dest", Connection = "EventHubConnection")]
    public string EventHubFunction(
        [EventHubTrigger("src", Connection = "EventHubConnection")] string[] input,
        FunctionContext context)
    {
        _logger.LogInformation("First Event Hubs triggered message: {msg}", input[0]);

        var message = $"Output message created at {DateTime.Now}";
        return message;
    }

The following example shows an Event Hubs trigger TypeScript function. The function reads event metadata and logs the message.

import { app, InvocationContext } from '@azure/functions';

export async function eventHubTrigger1(message: unknown, context: InvocationContext): Promise<void> {
    context.log('Event hub function processed message:', message);
    context.log('EnqueuedTimeUtc =', context.triggerMetadata.enqueuedTimeUtc);
    context.log('SequenceNumber =', context.triggerMetadata.sequenceNumber);
    context.log('Offset =', context.triggerMetadata.offset);
}

app.eventHub('eventHubTrigger1', {
    connection: 'myEventHubReadConnectionAppSetting',
    eventHubName: 'MyEventHub',
    cardinality: 'one',
    handler: eventHubTrigger1,
});

To receive events in a batch, set cardinality to many, as shown in the following example.

import { app, InvocationContext } from '@azure/functions';

export async function eventHubTrigger1(messages: unknown[], context: InvocationContext): Promise<void> {
    context.log(`Event hub function processed ${messages.length} messages`);
    for (let i = 0; i < messages.length; i++) {
        context.log('Event hub message:', messages[i]);
        context.log(`EnqueuedTimeUtc = ${context.triggerMetadata.enqueuedTimeUtcArray[i]}`);
        context.log(`SequenceNumber = ${context.triggerMetadata.sequenceNumberArray[i]}`);
        context.log(`Offset = ${context.triggerMetadata.offsetArray[i]}`);
    }
}

app.eventHub('eventHubTrigger1', {
    connection: 'myEventHubReadConnectionAppSetting',
    eventHubName: 'MyEventHub',
    cardinality: 'many',
    handler: eventHubTrigger1,
});

The following example shows an Event Hubs trigger JavaScript function. The function reads event metadata and logs the message.

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

app.eventHub('eventHubTrigger1', {
    connection: 'myEventHubReadConnectionAppSetting',
    eventHubName: 'MyEventHub',
    cardinality: 'one',
    handler: (message, context) => {
        context.log('Event hub function processed message:', message);
        context.log('EnqueuedTimeUtc =', context.triggerMetadata.enqueuedTimeUtc);
        context.log('SequenceNumber =', context.triggerMetadata.sequenceNumber);
        context.log('Offset =', context.triggerMetadata.offset);
    },
});

To receive events in a batch, set cardinality to many, as shown in the following example.

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

app.eventHub('eventHubTrigger1', {
    connection: 'myEventHubReadConnectionAppSetting',
    eventHubName: 'MyEventHub',
    cardinality: 'many',
    handler: (messages, context) => {
        context.log(`Event hub function processed ${messages.length} messages`);
        for (let i = 0; i < messages.length; i++) {
            context.log('Event hub message:', messages[i]);
            context.log(`EnqueuedTimeUtc = ${context.triggerMetadata.enqueuedTimeUtcArray[i]}`);
            context.log(`SequenceNumber = ${context.triggerMetadata.sequenceNumberArray[i]}`);
            context.log(`Offset = ${context.triggerMetadata.offsetArray[i]}`);
        }
    },
});

Here's the PowerShell code:

param($eventHubMessages, $TriggerMetadata)

Write-Host "PowerShell eventhub trigger function called for message array: $eventHubMessages"

$eventHubMessages | ForEach-Object { Write-Host "Processed message: $_" }

The following example shows an Event Hubs trigger binding and a Python function that uses the binding. The function reads event metadata and logs the message. The example depends on whether you use the v1 or v2 Python programming model.

import logging
import azure.functions as func

app = func.FunctionApp()

@app.function_name(name="EventHubTrigger1")
@app.event_hub_message_trigger(arg_name="myhub", 
                               event_hub_name="<EVENT_HUB_NAME>",
                               connection="<CONNECTION_SETTING>") 
def test_function(myhub: func.EventHubEvent):
    logging.info('Python EventHub trigger processed an event: %s',
                myhub.get_body().decode('utf-8'))

The following example shows an Event Hubs trigger binding which logs the message body of the Event Hubs trigger.

@FunctionName("ehprocessor")
public void eventHubProcessor(
  @EventHubTrigger(name = "msg",
                  eventHubName = "myeventhubname",
                  connection = "myconnvarname") String message,
       final ExecutionContext context )
       {
          context.getLogger().info(message);
 }

In the Java functions runtime library, use the EventHubTrigger annotation on parameters whose value comes from the event hub. Parameters with these annotations cause the function to run when an event arrives. This annotation can be used with native Java types, POJOs, or nullable values using Optional<T>.

The following example illustrates extensive use of SystemProperties and other Binding options for further introspection of the Event along with providing a well-formed BlobOutput path that is Date hierarchical.

package com.example;
import java.util.Map;
import java.time.ZonedDateTime;

import com.microsoft.azure.functions.annotation.*;
import com.microsoft.azure.functions.*;

/**
 * Azure Functions with Event Hub trigger.
 * and Blob Output using date in path along with message partition ID
 * and message sequence number from EventHub Trigger Properties
 */
public class EventHubReceiver {

    @FunctionName("EventHubReceiver")
    @StorageAccount("bloboutput")

    public void run(
            @EventHubTrigger(name = "message",
                eventHubName = "%eventhub%",
                consumerGroup = "%consumergroup%",
                connection = "eventhubconnection",
                cardinality = Cardinality.ONE)
            String message,

            final ExecutionContext context,

            @BindingName("Properties") Map<String, Object> properties,
            @BindingName("SystemProperties") Map<String, Object> systemProperties,
            @BindingName("PartitionContext") Map<String, Object> partitionContext,
            @BindingName("EnqueuedTimeUtc") Object enqueuedTimeUtc,

            @BlobOutput(
                name = "outputItem",
                path = "iotevents/{datetime:yy}/{datetime:MM}/{datetime:dd}/{datetime:HH}/" +
                       "{datetime:mm}/{PartitionContext.PartitionId}/{SystemProperties.SequenceNumber}.json")
            OutputBinding<String> outputItem) {

        var et = ZonedDateTime.parse(enqueuedTimeUtc + "Z"); // needed as the UTC time presented does not have a TZ
                                                             // indicator
        context.getLogger().info("Event hub message received: " + message + ", properties: " + properties);
        context.getLogger().info("Properties: " + properties);
        context.getLogger().info("System Properties: " + systemProperties);
        context.getLogger().info("partitionContext: " + partitionContext);
        context.getLogger().info("EnqueuedTimeUtc: " + et);

        outputItem.setValue(message);
    }
}

Attributes

Both in-process and isolated worker process C# libraries use attribute to configure the trigger. C# script instead uses a function.json configuration file as described in the C# scripting guide.

Use the EventHubTriggerAttribute to define a trigger on an event hub, which supports the following properties.

Parameters Description
EventHubName The name of the event hub. When the event hub name is also present in the connection string, that value overrides this property at runtime. Can be referenced in app settings, like %eventHubName%
ConsumerGroup An optional property that sets the consumer group used to subscribe to events in the hub. When omitted, the $Default consumer group is used.
Connection The name of an app setting or setting collection that specifies how to connect to Event Hubs. To learn more, see Connections.

Decorators

Applies only to the Python v2 programming model.

For Python v2 functions defined using a decorator, the following properties on the event_hub_message_trigger:

Property Description
arg_name The name of the variable that represents the event item in function code.
event_hub_name The name of the event hub. When the event hub name is also present in the connection string, that value overrides this property at runtime.
connection The name of an app setting or setting collection that specifies how to connect to Event Hubs. See Connections.

For Python functions defined by using function.json, see the Configuration section.

Annotations

In the Java functions runtime library, use the EventHubTrigger annotation, which supports the following settings:

Configuration

Applies only to the Python v1 programming model.

The following table explains the properties that you can set on the options object passed to the app.eventHub() method.

Property Description
eventHubName The name of the event hub. When the event hub name is also present in the connection string, that value overrides this property at runtime. Can be referenced via app settings %eventHubName%
consumerGroup An optional property that sets the consumer group used to subscribe to events in the hub. If omitted, the $Default consumer group is used.
cardinality Set to many in order to enable batching. If omitted or set to one, a single message is passed to the function.
connection The name of an app setting or setting collection that specifies how to connect to Event Hubs. See Connections.

The following table explains the trigger configuration properties that you set in the function.json file, which differs by runtime version.

function.json property Description
type Must be set to eventHubTrigger. This property is set automatically when you create the trigger in the Azure portal.
direction Must be set to in. This property is set automatically when you create the trigger in the Azure portal.
name The name of the variable that represents the event item in function code.
eventHubName The name of the event hub. When the event hub name is also present in the connection string, that value overrides this property at runtime. Can be referenced via app settings %eventHubName%
consumerGroup An optional property that sets the consumer group used to subscribe to events in the hub. If omitted, the $Default consumer group is used.
cardinality Set to many in order to enable batching. If omitted or set to one, a single message is passed to the function.
connection The name of an app setting or setting collection that specifies how to connect to Event Hubs. See Connections.

When you're developing locally, add your application settings in the local.settings.json file in the Values collection.

Usage

To learn more about how Event Hubs trigger and IoT Hub trigger scales, see Consuming Events with Azure Functions.

The parameter type supported by the Event Hubs output binding depends on the Functions runtime version, the extension package version, and the C# modality used.

When you want the function to process a single event, the Event Hubs trigger can bind to the following types:

Type Description
string The event as a string. Use when the event is simple text.
byte[] The bytes of the event.
JSON serializable types When an event contains JSON data, Functions tries to deserialize the JSON data into a plain-old CLR object (POCO) type.
Azure.Messaging.EventHubs.EventData1 The event object.
If you are migrating from any older versions of the Event Hubs SDKs, note that this version drops support for the legacy Body type in favor of EventBody.

When you want the function to process a batch of events, the Event Hubs trigger can bind to the following types:

Type Description
string[] An array of events from the batch, as strings. Each entry represents one event.
EventData[] 1 An array of events from the batch, as instances of Azure.Messaging.EventHubs.EventData. Each entry represents one event.
T[] where T is a JSON serializable type1 An array of events from the batch, as instances of a custom POCO type. Each entry represents one event.

1 To use these types, you need to reference Microsoft.Azure.Functions.Worker.Extensions.EventHubs 5.5.0 or later and the common dependencies for SDK type bindings.

The parameter type can be one of the following:

  • Any native Java types such as int, String, byte[].
  • Nullable values using Optional.
  • Any POJO type.

To learn more, see the EventHubTrigger reference.

Event metadata

The Event Hubs trigger provides several metadata properties. Metadata properties can be used as part of binding expressions in other bindings or as parameters in your code. The properties come from the EventData class.

Property Type Description
PartitionContext PartitionContext The PartitionContext instance.
EnqueuedTimeUtc DateTime The enqueued time in UTC.
Offset string The offset of the data relative to the event hub partition stream. The offset is a marker or identifier for an event within the Event Hubs stream. The identifier is unique within a partition of the Event Hubs stream.
PartitionKey string The partition to which event data should be sent.
Properties IDictionary<String,Object> The user properties of the event data.
SequenceNumber Int64 The logical sequence number of the event.
SystemProperties IDictionary<String,Object> The system properties, including the event data.

See code examples that use these properties earlier in this article.

Connections

The connection property is a reference to environment configuration which specifies how the app should connect to Event Hubs. It may specify:

If the configured value is both an exact match for a single setting and a prefix match for other settings, the exact match is used.

Connection string

Obtain this connection string by clicking the Connection Information button for the namespace, not the event hub itself. The connection string must be for an Event Hubs namespace, not the event hub itself.

When used for triggers, the connection string must have at least "read" permissions to activate the function. When used for output bindings, the connection string must have "send" permissions to send messages to the event stream.

This connection string should be stored in an application setting with a name matching the value specified by the connection property of the binding configuration.

Identity-based connections

If you are using version 5.x or higher of the extension, instead of using a connection string with a secret, you can have the app use an Microsoft Entra identity. To do this, you would define settings under a common prefix which maps to the connection property in the trigger and binding configuration.

In this mode, the extension requires the following properties:

Property Environment variable template Description Example value
Fully Qualified Namespace <CONNECTION_NAME_PREFIX>__fullyQualifiedNamespace The fully qualified Event Hubs namespace. myeventhubns.servicebus.windows.net

Additional properties may be set to customize the connection. See Common properties for identity-based connections.

Note

When using Azure App Configuration or Key Vault to provide settings for Managed Identity connections, setting names should use a valid key separator such as : or / in place of the __ to ensure names are resolved correctly.

For example, <CONNECTION_NAME_PREFIX>:fullyQualifiedNamespace.

When hosted in the Azure Functions service, identity-based connections use a managed identity. The system-assigned identity is used by default, although a user-assigned identity can be specified with the credential and clientID properties. Note that configuring a user-assigned identity with a resource ID is not supported. When run in other contexts, such as local development, your developer identity is used instead, although this can be customized. See Local development with identity-based connections.

Grant permission to the identity

Whatever identity is being used must have permissions to perform the intended actions. For most Azure services, this means you need to assign a role in Azure RBAC, using either built-in or custom roles which provide those permissions.

Important

Some permissions might be exposed by the target service that are not necessary for all contexts. Where possible, adhere to the principle of least privilege, granting the identity only required privileges. For example, if the app only needs to be able to read from a data source, use a role that only has permission to read. It would be inappropriate to assign a role that also allows writing to that service, as this would be excessive permission for a read operation. Similarly, you would want to ensure the role assignment is scoped only over the resources that need to be read.

You will need to create a role assignment that provides access to your event hub at runtime. The scope of the role assignment can be for an Event Hubs namespace, or the event hub itself. Management roles like Owner are not sufficient. The following table shows built-in roles that are recommended when using the Event Hubs extension in normal operation. Your application may require additional permissions based on the code you write.

Binding type Example built-in roles
Trigger Azure Event Hubs Data Receiver, Azure Event Hubs Data Owner
Output binding Azure Event Hubs Data Sender

host.json settings

The host.json file contains settings that control Event Hubs trigger behavior. See the host.json settings section for details regarding available settings.

Next steps