Sending Messages to Service Bus

Azure Functions provide output bindings for sending messages to Azure Service Bus queues and topics. This allows you to easily integrate your serverless code with Service Bus destinations without manual SDK interactions.

Supported Service Bus Entities

You can send messages to the following Service Bus entities:

  • Queues: For point-to-point messaging.
  • Topics: For publish-subscribe messaging patterns.

Trigger and Binding Configuration

The configuration is typically done in the function.json file for your function. Here's an example for a Service Bus queue output binding:


{
  "bindings": [
    {
      "name": "msg",
      "type": "queue",
      "direction": "out",
      "queueName": "myoutputqueue",
      "connection": "ServiceBusConnectionString"
    }
  ]
}
                    

In this example:

  • "name": "msg": This is the name of the parameter in your function code that will hold the message to be sent.
  • "type": "queue": Specifies that this is an output binding for a Service Bus queue. For topics, you would use "type": "topic".
  • "direction": "out": Indicates this is an output binding.
  • "queueName": "myoutputqueue": The name of the Service Bus queue to send messages to. For topics, this would be "topicName".
  • "connection": "ServiceBusConnectionString": The name of the application setting that contains your Service Bus connection string.

Programming Model Examples

C# Example

When using the C# class library programming model, you can define the output binding using attributes:


using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;

public static class ServiceBusSender
{
    [FunctionName("SendToQueue")]
    public static void Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
        [Queue("myoutputqueue", Connection = "ServiceBusConnectionString")] out string msg,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");

        string name = req.Query["name"];
        string requestBody = new StreamReader(req.Body).ReadToEnd();
        dynamic data = JsonConvert.DeserializeObject(requestBody);
        name = name ?? data?.name;

        if (name != null)
        {
            string responseMessage = $"Hello, {name}. This HTTP triggered function executed successfully. Sending a message to Service Bus.";
            msg = $"Message for {name}: Processed at {DateTime.UtcNow}";
            log.LogInformation($"Message prepared for Service Bus: {msg}");
            return new OkObjectResult(responseMessage);
        }
        else
        {
            return new BadRequestObjectResult("Please pass a name in the query string or in the request body");
        }
    }
}
                    

JavaScript Example

In JavaScript, the output binding is configured in function.json and accessed via the context object in your function code.

// Function: index.js
module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    const name = (req.query.name || (req.body && req.body.name));
    const responseMessage = name
        ? 'Hello, ' + name + '. This HTTP triggered function executed successfully. Sending a message to Service Bus.'
        : 'This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.';

    context.bindings.msg = `Message for ${name || 'anonymous'}: Processed at ${new Date().toISOString()}`;
    context.log(`Message prepared for Service Bus: ${context.bindings.msg}`);

    context.res = {
        status: 200,
        body: responseMessage
    };
};
                    
// Function: function.json
{
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    },
    {
      "name": "msg",
      "type": "queue",
      "direction": "out",
      "queueName": "myoutputqueue",
      "connection": "ServiceBusConnectionString"
    }
  ]
}
                    

Sending to Topics

To send messages to a Service Bus topic, change the "type" to "topic" and use the "topicName" property instead of "queueName":


{
  "bindings": [
    {
      "name": "msg",
      "type": "topic",
      "direction": "out",
      "topicName": "mytopic",
      "connection": "ServiceBusConnectionString"
    }
  ]
}
                    
Important: Ensure the Service Bus connection string in your application settings is correctly configured and has the necessary permissions to send messages to the specified queue or topic.

Advanced Scenarios

For more complex scenarios, such as sending message properties or batching messages, you might need to use the Azure SDK directly within your function code. However, for most common use cases, the output binding provides a straightforward and efficient solution.