Using an Azure Service Bus Topic Subscription in an Azure Function

This post shows how to consume Azure service bus topic subscriptions in an Azure function.

Code: https://github.com/damienbod/AspNetCoreServiceBus

Posts in this series:

Processing the Azure Service Bus Messages in an Azure Function

Setting this up could not be easier. In Visual Studio, create a new Azure function project, and then create a new Azure function using the Visual Studio helpers.

Select a Service Bus Topic trigger and add the definitions as required. These can be changed later, if you don’t know the required values.

The new Azure function has an attribute which is used to defined the client for the topic subscription. The service bus connection string is defined as ServiceBusConnectionString. This will be specified later. The message is then deserialized to an object. Now you can handle the payload as required.

using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace FunctionService3
{
    public static class SubscriptionClientFunction
    {
        [FunctionName("SubscriptionClientFunction")]
        public static void Run([ServiceBusTrigger(
            "mytopic", 
            "functionsubscription",
            Connection = "ServiceBusConnectionString")]string message, ILogger log)
        {
            log.LogInformation($"C# ServiceBus topic trigger function processed message: {message}");

            var payload = JsonConvert.DeserializeObject<MyPayload>(message);
        }
    }
}

The connection for the Azure service bus is defined in the local.settings.json file. This is a bit of a problem because we should not be committing this secret value to our source code repository. We could use a dev service bus here, and commit this then. The test and production service bus connection strings could then be set as part of the build.

Azure Key Vault could also be used to get the service bus connection string. This is only a little bit better as the key vault secret would be pushed to the server, so we still have a secret in our code.

It would be nice if we could use something like the Microsoft extensions key vault configuration where no secret is required to use the key vault.

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "ServiceBusConnectionString": "Not possible to read from a secret src without a another"
  },
  "Host": {
    "LocalHttpPort": "7071",
    "CORS":  "*"
  }
}

The Azure service bus subscription needs to be configured in Azure:

It is really easy to use Azure service bus with Azure functions. The handling of secrets could be improved. There are some open source projects which help solve this problem.

Links:

https://docs.microsoft.com/en-us/azure/service-bus-messaging/

https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-dotnet-get-started-with-queues

https://www.nuget.org/packages/Microsoft.Azure.ServiceBus

Azure Service Bus Topologies

https://docs.microsoft.com/en-us/dotnet/standard/microservices-architecture/multi-container-microservice-net-applications/integration-event-based-microservice-communications

Always subscribe to Dead-lettered messages when using an Azure Service Bus

https://ml-software.ch/posts/stripe-api-with-asp-net-core-part-3

Auto Forwarding, a hidden gem of Service Bus

5 comments

  1. Schmallaria · · Reply

    Could you please share some information on how to debug azure functions? Especially those which uses ServiceBusTrigger.

    1. Hi Schmallaria
      For local dev, this should just work. The example in this blog is committed to the git repo, and it should just start. You need to install to local tools to run azure functions. Or do you mean directly on the deployment, like in Azure?

      Greetings Damien

  2. Schmallaria · · Reply

    Hi Damien,

    Yes, I mean local debugging. Could you explain what tools I need and what I have to do to start debugging? When I try to debug a Azure function with a ServiceBusTrigger I always get the error: “Cannot start the Azure Storage Emulator. Please run AzureStorageEmulator.exe start”.

    BR

    1. I added the links for the tools here:

      https://damienbod.com/2019/03/14/running-local-azure-functions-in-visual-studio-with-https/

      install the tools from the 3 links, and you will be able to debug, run locally

      Greetings Damien

      1. Schmallaria · ·

        Hi Damien,

        many thanks. That helped me. I had trouble with my localDB instance which was not correct configured thus the emulator didn’t start. After re-installing all required tools (mentioned in your link) everything is working as expected.

        BR

Leave a Reply to Schmallaria Cancel reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: