Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
This article explains how to work with Azure Event Hubs bindings 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 Event Hubs output binding to write events to an event stream. You must have send permission to an event hub to write events to it.
Make sure the required package references are in place before you try to implement an output binding.
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
Go support isn't currently available for this binding.
The following example shows a C# function that writes a message string to an event hub, using the method return value as the output:
[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 a timer triggered TypeScript function that sends a single message to an event hub:
import { app, InvocationContext, output, Timer } from '@azure/functions';
export async function timerTrigger1(myTimer: Timer, context: InvocationContext): Promise<string> {
const timeStamp = new Date().toISOString();
return `Message created at: ${timeStamp}`;
}
app.timer('timerTrigger1', {
schedule: '0 */5 * * * *',
return: output.eventHub({
eventHubName: 'myeventhub',
connection: 'MyEventHubSendAppSetting',
}),
handler: timerTrigger1,
});
To output multiple messages, return an array instead of a single object. For example:
const timeStamp = new Date().toISOString();
const message = `Message created at: ${timeStamp}`;
return [`1: ${message}`, `2: ${message}`];
The following example shows a timer triggered JavaScript function that sends a single message to an event hub:
const { app, output } = require('@azure/functions');
const eventHubOutput = output.eventHub({
eventHubName: 'myeventhub',
connection: 'MyEventHubSendAppSetting',
});
app.timer('timerTrigger1', {
schedule: '0 */5 * * * *',
return: eventHubOutput,
handler: (myTimer, context) => {
const timeStamp = new Date().toISOString();
return `Message created at: ${timeStamp}`;
},
});
To output multiple messages, return an array instead of a single object. For example:
const timeStamp = new Date().toISOString();
const message = `Message created at: ${timeStamp}`;
return [`1: ${message}`, `2: ${message}`];
Complete PowerShell examples are pending.
The following example shows an event hub trigger binding and a Python function that uses the binding. The function writes a message to an event hub. 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="eventhub_output")
@app.route(route="eventhub_output")
@app.event_hub_output(arg_name="event",
event_hub_name="<EVENT_HUB_NAME>",
connection="<CONNECTION_SETTING>")
def eventhub_output(req: func.HttpRequest, event: func.Out[str]):
body = req.get_body()
if body is not None:
event.set(body.decode('utf-8'))
else:
logging.info('req body is none')
return 'ok'
Here's Python code that sends multiple messages:
import logging
import azure.functions as func
from typing import List
app = func.FunctionApp()
@app.function_name(name="eventhub_output")
@app.route(route="eventhub_output")
@app.event_hub_output(arg_name="event",
event_hub_name="<EVENT_HUB_NAME>",
connection="<CONNECTION_SETTING>")
def eventhub_output(req: func.HttpRequest, event: func.Out[List[str]]) -> func.HttpResponse:
my_messages=["message1", "message2","message3"]
event.set(my_messages)
return func.HttpResponse(f"Messages sent")
The following example shows a Java function that writes a message containing the current time to an event hub.
@FunctionName("sendTime")
@EventHubOutput(name = "event", eventHubName = "samples-workitems", connection = "AzureEventHubConnection")
public String sendTime(
@TimerTrigger(name = "sendTimeTrigger", schedule = "0 */5 * * * *") String timerInfo) {
return LocalDateTime.now().toString();
}
In the Java functions runtime library, use the @EventHubOutput annotation on parameters whose value would be published to Event Hubs. The parameter should be of type OutputBinding<T> , where T is a POJO or any native Java type.
Attributes
Both in-process and isolated worker process C# libraries use attribute to configure the binding. C# script instead uses a function.json configuration file as described in the C# scripting guide.
Use the [EventHubOutputAttribute] to define an output binding to 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. |
| 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, these properties are supported for event_hub_output:
| Property | Description |
|---|---|
arg_name |
The variable name used in function code that represents the event. |
event_hub_name |
he 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. To learn more, see Connections. |
For Python functions defined by using function.json, see the Configuration section.
Annotations
In the Java functions runtime library, use the EventHubOutput annotation on parameters whose value would be published to Event Hubs. The following settings are supported on the annotation:
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 output.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. |
| connection | The name of an app setting or setting collection that specifies how to connect to Event Hubs. To learn more, see Connections. |
The following table explains the binding configuration properties that you set in the function.json file, which differs by runtime version.
| function.json property | Description |
|---|---|
| type | Must be set to eventHub. |
| direction | Must be set to out. This parameter is set automatically when you create the binding in the Azure portal. |
| name | The variable name used in function code that represents the event. |
| eventHubName | Functions 2.x and higher. 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. To learn more, see Connections. |
When you're developing locally, add your application settings in the local.settings.json file in the Values collection.
Usage
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 write a single event, the Event Hubs output binding 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 | An object representing the event. Functions tries to serialize a plain-old CLR object (POCO) type into JSON data. |
When you want the function to write multiple events, the Event Hubs output binding can bind to the following types:
| Type | Description |
|---|---|
T[] where T is one of the single event types |
An array containing multiple events. Each entry represents one event. |
For other output scenarios, create and use an EventHubProducerClient with other types from Azure.Messaging.EventHubs directly. See Register Azure clients for an example of using dependency injection to create a client type from the Azure SDK.
There are two options for outputting an Event Hubs message from a function by using the EventHubOutput annotation:
Return value: By applying the annotation to the function itself, the return value of the function is persisted as an Event Hubs message.
Imperative: To explicitly set the message value, apply the annotation to a specific parameter of the type
OutputBinding<T>, whereTis a POJO or any native Java type. With this configuration, passing a value to thesetValuemethod persists the value as an Event Hubs message.
Complete PowerShell examples are pending.
There are two options for outputting an Event Hubs message from a function:
Return value: Set the
nameproperty in function.json to$return. With this configuration, the function's return value is persisted as an Event Hubs message.Imperative: Pass a value to the set method of the parameter declared as an Out type. The value passed to
setis persisted as an Event Hubs message.
The output function parameter must be defined as func.Out[func.EventHubEvent] or func.Out[List[func.EventHubEvent]]. Refer to the output example for details.
Connections
The connection property is set to a key in application settings that returns a value used by the Functions runtime to connect to the Event Hubs namespace that contains the event hub used by the extension. The value of the connection property setting depends on the type of connection:
- Managed identity connection: The
connectionproperty is a<CONNECTION_NAME_PREFIX>shared by a group of settings that together define an identity-based connection to the namespace. For more information, see Define identity connections. - Key Vault reference: The
connectionproperty setting returns an Azure Key Vault reference to the location where the connection string is centrally maintained. For more information, see Define Key Vault connections. - App Configuration reference: The
connectionproperty setting returns an Azure App Configuration reference that returns a connection string or a Key Vault reference. For more information, see Azure App Configuration in the connections article. - Connection string: The
connectionproperty setting returns the actual connection string of the namespace. The connection string must be for an Event Hubs namespace, not the event hub itself. Because the connection string contains shared secret keys, you should consider using a managed identity connection, when possible. For more information, see Define connections.
To learn more about bindings connections, see Manage connection in Azure Functions.
To learn how to obtain the connection string for your Event Hubs namespace, see Get an Event Hubs connection string.
Exceptions and return codes
| Binding | Reference |
|---|---|
| Event Hubs | Operations Guide |