title | description | ms.assetid | ms.topic | ms.date | ms.devlang | ms.custom | zone_pivot_groups |
---|---|---|---|---|---|---|---|
Azure Service Bus output bindings for Azure Functions |
Learn to send Azure Service Bus messages from Azure Functions. |
daedacf0-6546-4355-a65c-50873e74f66b |
reference |
03/04/2022 |
csharp, java, javascript, powershell, python |
devx-track-csharp, devx-track-python |
programming-languages-set-functions-lang-workers |
Use Azure Service Bus output binding to send queue or topic messages.
For information on setup and configuration details, see the overview.
::: zone pivot="programming-language-csharp"
[!INCLUDE functions-bindings-csharp-intro]
The following example shows a C# function that sends a Service Bus queue message:
[FunctionName("ServiceBusOutput")]
[return: ServiceBus("myqueue", Connection = "ServiceBusConnection")]
public static string ServiceBusOutput([HttpTrigger] dynamic input, ILogger log)
{
log.LogInformation($"C# function processed: {input.Text}");
return input.Text;
}
The following example shows a C# function that receives a Service Bus queue message, logs the message, and sends a message to different Service Bus queue:
:::code language="csharp" source="~/azure-functions-dotnet-worker/samples/Extensions/ServiceBus/ServiceBusFunction.cs" range="10-25":::
The following example shows a Service Bus output binding in a function.json file and a C# script function that uses the binding. The function uses a timer trigger to send a queue message every 15 seconds.
Here's the binding data in the function.json file:
{
"bindings": [
{
"schedule": "0/15 * * * * *",
"name": "myTimer",
"runsOnStartup": true,
"type": "timerTrigger",
"direction": "in"
},
{
"name": "outputSbQueue",
"type": "serviceBus",
"queueName": "testqueue",
"connection": "MyServiceBusConnection",
"direction": "out"
}
],
"disabled": false
}
Here's C# script code that creates a single message:
public static void Run(TimerInfo myTimer, ILogger log, out string outputSbQueue)
{
string message = $"Service Bus queue message created at: {DateTime.Now}";
log.LogInformation(message);
outputSbQueue = message;
}
Here's C# script code that creates multiple messages:
public static async Task Run(TimerInfo myTimer, ILogger log, IAsyncCollector<string> outputSbQueue)
{
string message = $"Service Bus queue messages created at: {DateTime.Now}";
log.LogInformation(message);
await outputSbQueue.AddAsync("1 " + message);
await outputSbQueue.AddAsync("2 " + message);
}
::: zone-end ::: zone pivot="programming-language-java"
The following example shows a Java function that sends a message to a Service Bus queue myqueue
when triggered by an HTTP request.
@FunctionName("httpToServiceBusQueue")
@ServiceBusQueueOutput(name = "message", queueName = "myqueue", connection = "AzureServiceBusConnection")
public String pushToQueue(
@HttpTrigger(name = "request", methods = {HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS)
final String message,
@HttpOutput(name = "response") final OutputBinding<T> result ) {
result.setValue(message + " has been sent.");
return message;
}
In the Java functions runtime library, use the @QueueOutput
annotation on function parameters whose value would be written to a Service Bus queue. The parameter type should be OutputBinding<T>
, where T is any native Java type of a POJO.
Java functions can also write to a Service Bus topic. The following example uses the @ServiceBusTopicOutput
annotation to describe the configuration for the output binding.
@FunctionName("sbtopicsend")
public HttpResponseMessage run(
@HttpTrigger(name = "req", methods = {HttpMethod.GET, HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request,
@ServiceBusTopicOutput(name = "message", topicName = "mytopicname", subscriptionName = "mysubscription", connection = "ServiceBusConnection") OutputBinding<String> message,
final ExecutionContext context) {
String name = request.getBody().orElse("Azure Functions");
message.setValue(name);
return request.createResponseBuilder(HttpStatus.OK).body("Hello, " + name).build();
}
::: zone-end
::: zone pivot="programming-language-javascript"
The following example shows a Service Bus output binding in a function.json file and a JavaScript function that uses the binding. The function uses a timer trigger to send a queue message every 15 seconds.
Here's the binding data in the function.json file:
{
"bindings": [
{
"schedule": "0/15 * * * * *",
"name": "myTimer",
"runsOnStartup": true,
"type": "timerTrigger",
"direction": "in"
},
{
"name": "outputSbQueue",
"type": "serviceBus",
"queueName": "testqueue",
"connection": "MyServiceBusConnection",
"direction": "out"
}
],
"disabled": false
}
Here's JavaScript script code that creates a single message:
module.exports = async function (context, myTimer) {
var message = 'Service Bus queue message created at ' + timeStamp;
context.log(message);
context.bindings.outputSbQueue = message;
};
Here's JavaScript script code that creates multiple messages:
module.exports = async function (context, myTimer) {
var message = 'Service Bus queue message created at ' + timeStamp;
context.log(message);
context.bindings.outputSbQueue = [];
context.bindings.outputSbQueue.push("1 " + message);
context.bindings.outputSbQueue.push("2 " + message);
};
::: zone-end
::: zone pivot="programming-language-powershell"
The following example shows a Service Bus output binding in a function.json file and a PowerShell function that uses the binding.
Here's the binding data in the function.json file:
{
"bindings": [
{
"type": "serviceBus",
"direction": "out",
"connection": "AzureServiceBusConnectionString",
"name": "outputSbMsg",
"queueName": "outqueue",
"topicName": "outtopic"
}
]
}
Here's the PowerShell that creates a message as the function's output.
param($QueueItem, $TriggerMetadata)
Push-OutputBinding -Name outputSbMsg -Value @{
name = $QueueItem.name
employeeId = $QueueItem.employeeId
address = $QueueItem.address
}
::: zone-end
::: zone pivot="programming-language-python"
The following example demonstrates how to write out to a Service Bus queue in Python.
A Service Bus binding definition is defined in function.json where type is set to serviceBus
.
{
"scriptFile": "__init__.py",
"bindings": [
{
"authLevel": "function",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"get",
"post"
]
},
{
"type": "http",
"direction": "out",
"name": "$return"
},
{
"type": "serviceBus",
"direction": "out",
"connection": "AzureServiceBusConnectionString",
"name": "msg",
"queueName": "outqueue"
}
]
}
In _init_.py, you can write out a message to the queue by passing a value to the set
method.
import azure.functions as func
def main(req: func.HttpRequest, msg: func.Out[str]) -> func.HttpResponse:
input_msg = req.params.get('message')
msg.set(input_msg)
return 'OK'
::: zone-end
::: zone pivot="programming-language-csharp"
Both in-process and isolated process C# libraries use attributes to define the output binding. C# script instead uses a function.json configuration file.
In C# class libraries, use the ServiceBusAttribute.
The following table explains the properties you can set using the attribute:
Property | Description |
---|---|
QueueName | Name of the queue. Set only if sending queue messages, not for a topic. |
TopicName | Name of the topic. Set only if sending topic messages, not for a queue. |
Connection | The name of an app setting or setting collection that specifies how to connect to Service Bus. See Connections. |
Access | Access rights for the connection string. Available values are manage and listen . The default is manage , which indicates that the connection has the Manage permission. If you use a connection string that does not have the Manage permission, set accessRights to "listen". Otherwise, the Functions runtime might fail trying to do operations that require manage rights. In Azure Functions version 2.x and higher, this property is not available because the latest version of the Service Bus SDK doesn't support manage operations. |
Here's an example that shows the attribute applied to the return value of the function:
[FunctionName("ServiceBusOutput")]
[return: ServiceBus("myqueue")]
public static string Run([HttpTrigger] dynamic input, ILogger log)
{
...
}
You can set the Connection
property to specify the name of an app setting that contains the Service Bus connection string to use, as shown in the following example:
[FunctionName("ServiceBusOutput")]
[return: ServiceBus("myqueue", Connection = "ServiceBusConnection")]
public static string Run([HttpTrigger] dynamic input, ILogger log)
{
...
}
For a complete example, see Example.
You can use the ServiceBusAccount
attribute to specify the Service Bus account to use at class, method, or parameter level. For more information, see Attributes in the trigger reference.
In C# class libraries, use the ServiceBusOutputAttribute to define the queue or topic written to by the output.
The following table explains the properties you can set using the attribute:
Property | Description |
---|---|
EntityType | Sets the entity type as either Queue for sending messages to a queue or Topic when sending messages to a topic. |
QueueOrTopicName | Name of the topic or queue to send messages to. Use EntityType to set the destination type. |
Connection | The name of an app setting or setting collection that specifies how to connect to Service Bus. See Connections. |
C# script uses a function.json file for configuration instead of attributes. The following table explains the binding configuration properties that you set in the function.json file.
|function.json property | Description|
|---------|---------|----------------------|
|type |Must be set to "serviceBus". This property is set automatically when you create the trigger in the Azure portal.|
|direction | Must be set to "out". This property is set automatically when you create the trigger in the Azure portal. |
|name | The name of the variable that represents the queue or topic message in function code. Set to "$return" to reference the function return value. |
|queueName|Name of the queue. Set only if sending queue messages, not for a topic.
|topicName|Name of the topic. Set only if sending topic messages, not for a queue.|
|connection|The name of an app setting or setting collection that specifies how to connect to Service Bus. See Connections.|
|accessRights (v1 only)|Access rights for the connection string. Available values are manage
and listen
. The default is manage
, which indicates that the connection
has the Manage permission. If you use a connection string that does not have the Manage permission, set accessRights
to "listen". Otherwise, the Functions runtime might fail trying to do operations that require manage rights. In Azure Functions version 2.x and higher, this property is not available because the latest version of the Service Bus SDK doesn't support manage operations.|
::: zone-end
::: zone pivot="programming-language-java"
The ServiceBusQueueOutput
and ServiceBusTopicOutput
annotations are available to write a message as a function output. The parameter decorated with these annotations must be declared as an OutputBinding<T>
where T
is the type corresponding to the message's type.
[!INCLUDE app settings to local.settings.json]
::: zone-end
::: zone pivot="programming-language-javascript,programming-language-powershell,programming-language-python"
The following table explains the binding configuration properties that you set in the function.json file and the ServiceBus
attribute.
|function.json property | Description|
|---------|---------|----------------------|
|type |Must be set to "serviceBus". This property is set automatically when you create the trigger in the Azure portal.|
|direction | Must be set to "out". This property is set automatically when you create the trigger in the Azure portal. |
|name | The name of the variable that represents the queue or topic message in function code. Set to "$return" to reference the function return value. |
|queueName|Name of the queue. Set only if sending queue messages, not for a topic.
|topicName|Name of the topic. Set only if sending topic messages, not for a queue.|
|connection|The name of an app setting or setting collection that specifies how to connect to Service Bus. See Connections.|
|accessRights (v1 only)|Access rights for the connection string. Available values are manage
and listen
. The default is manage
, which indicates that the connection
has the Manage permission. If you use a connection string that does not have the Manage permission, set accessRights
to "listen". Otherwise, the Functions runtime might fail trying to do operations that require manage rights. In Azure Functions version 2.x and higher, this property is not available because the latest version of the Service Bus SDK doesn't support manage operations.|
[!INCLUDE app settings to local.settings.json]
::: zone-end
See the Example section for complete examples.
::: zone pivot="programming-language-csharp"
The following output parameter types are supported by all C# modalities and extension versions:
Type | Description |
---|---|
System.String | Use when the message to write is simple text. When the parameter value is null when the function exits, Functions doesn't create a message. |
byte[] | Use for writing binary data messages. When the parameter value is null when the function exits, Functions doesn't create a message. |
Object | When a message contains JSON, Functions serializes the object into a JSON message payload. When the parameter value is null when the function exits, Functions creates a message with a null object. |
Messaging-specific parameter types contain additional message metadata. The specific types supported by the Event Grid Output binding depend on the Functions runtime version, the extension package version, and the C# modality used.
Use the ServiceBusMessage type when sending messages with metadata. Parameters are defined as return
type attributes. Use an ICollector<T>
or IAsyncCollector<T>
to write multiple messages. A message is created when you call the Add
method.
When the parameter value is null when the function exits, Functions doesn't create a message.
[!INCLUDE functions-service-bus-account-attribute]
Use the Message type when sending messages with metadata. Parameters are defined as return
type attributes. Use an ICollector<T>
or IAsyncCollector<T>
to write multiple messages. A message is created when you call the Add
method.
When the parameter value is null when the function exits, Functions doesn't create a message.
[!INCLUDE functions-service-bus-account-attribute]
Use the BrokeredMessage type when sending messages with metadata. Parameters are defined as return
type attributes. When the parameter value is null when the function exits, Functions doesn't create a message.
[!INCLUDE functions-service-bus-account-attribute]
Messaging-specific types are not yet supported.
Messaging-specific types are not yet supported.
Messaging-specific types are not yet supported.
Use the ServiceBusMessage type when sending messages with metadata. Parameters are defined as out
parameters. Use an ICollector<T>
or IAsyncCollector<T>
to write multiple messages. A message is created when you call the Add
method.
When the parameter value is null when the function exits, Functions doesn't create a message.
Use the Message type when sending messages with metadata. Parameters are defined as out
parameters. Use an ICollector<T>
or IAsyncCollector<T>
to write multiple messages. A message is created when you call the Add
method.
When the parameter value is null when the function exits, Functions doesn't create a message.
Use the BrokeredMessage type when sending messages with metadata. Parameters are defined as out
parameters. Use an ICollector<T>
or IAsyncCollector<T>
to write multiple messages. A message is created when you call the Add
method.
When the parameter value is null when the function exits, Functions doesn't create a message.
::: zone-end
In Azure Functions 1.x, the runtime creates the queue if it doesn't exist and you have set accessRights
to manage
. In Functions version 2.x and higher, the queue or topic must already exist; if you specify a queue or topic that doesn't exist, the function fails.
::: zone pivot="programming-language-java"
Use the Azure Service Bus SDK rather than the built-in output binding.
::: zone-end
::: zone pivot="programming-language-javascript"
Access the queue or topic by using context.bindings.<name from function.json>
. You can assign a string, a byte array, or a JavaScript object (deserialized into JSON) to context.binding.<name>
.
::: zone-end
::: zone pivot="programming-language-powershell"
Output to the Service Bus is available via the Push-OutputBinding
cmdlet where you pass arguments that match the name designated by binding's name parameter in the function.json file.
::: zone-end
::: zone pivot="programming-language-python"
Use the Azure Service Bus SDK rather than the built-in output binding.
::: zone-end
For a complete example, see the examples section.
[!INCLUDE functions-service-bus-connections]
Binding | Reference |
---|---|
Service Bus | Service Bus Error Codes |
Service Bus | Service Bus Limits |