Azure Service Bus is a generic, Cloud-based messaging system. It connects apps running on Azure, on-premises systems or both. There are four different communication mechanisms of connection, each of which connects applications in a different way.
- Queues, allow one-directional communication. Each queue acts as an intermediary (broker) that stores sent messages until they are received. Each message is received by a single recipient.
- Topics, provids one-directional communication using subscriptions, a single topic can have multiple subscriptions. Like a queue, a topic acts as a broker, but each subscription can optionally use a filter to receive only messages that match specific criteria.
- Relays, provide bi-directional communication. Unlike queues and topics, a relay doesn't store messages. Instead, it just passes them on to the destination application.
- Event Hubs, is a highly scalable ingestion system that can process millions of events per second, enabling application to process and analyze the massive amounts of data produced by the connected devices and applications.
We can use one or more instances of four communication mechanisms depending on our requirement.
Reference - Azure Service Bus.
Creating Service Bus Namespace,
- Log on to the Azure portal.
- Click On New button. Select Hybrid Integration and select Service Bus.
- Click on Create button at bottom.
- Provide input as below and click Ok.
Using Service Bus Queue
Creating Service Bus Queue using Management Portal
- Once created select Service Namespace and select Queue option.
- Click on Create New Queue. Select Quick Create and provide the inputs.
- Click Create A New Queue.
Creating Service Bus Queue programmatically
- Open Visual Studio and create new console application.
- In Solution Explorer, right-click References, then click Manage NuGet Packages.
- Select the Microsoft Azure Service Bus item. Click Install.
- Open App.confgig file, under appSettings you can see key for Connection String is added as below.
- <appSettings>
- <!-- Service Bus specific app setings for messaging connections -->
- <addkey="Microsoft.ServiceBus.ConnectionString"
- value="Endpoint=sb://[your namespace].servicebus.windows.net;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=[your secret]"/>
-
- </appSettings>
- Go to Management portal. Click on Configuration Information button at bottom.
- Copy the connection string and replace value of connectionString key in App.config file.
- Write below code in program.cs file.
Add the following references.
- using Microsoft.ServiceBus;
- using Microsoft.WindowsAzure;
Add the following code in Main() method
- stringconnectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
-
- var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
-
- if (!namespaceManager.QueueExists("azservicequeue"))
- {
- namespaceManager.CreateQueue("azservicequeue");
- }
This will create "azservicequeue" service bus queue.
Send messages to a queue
- string connStr = "[connection string]";
- MessagingFactory factory = MessagingFactory.CreateFromConnectionString(connStr);
- MessageSendertestQueueSender = factory.CreateMessageSender("azservicequeue");
- BrokeredMessage message = new BrokeredMessage("This is sample message.");
- testQueueSender.Send(message);
Retrieve message form queue
- string connStr = "[connection string]";
- QueueClient Client = QueueClient.CreateFromConnectionString(connStr, "azservicequeue");
- OnMessageOptions options = newOnMessageOptions();
- options.AutoComplete = false;
- options.AutoRenewTimeout = TimeSpan.FromMinutes(1);
- Client.OnMessage((message) =>
- {
- try
- {
- Console.WriteLine("Message: " + message.GetBody < string > ());
-
- message.Complete();
- }
- catch (Exception)
- {
-
- message.Abandon();
- }
- }, options);
Message can be retrieve in two different mode
RecieveAndDelete or
PeekLock.
By default, a message is retrieved using the PeekLock mode, this means that the message is locked on the queue so that it cannot be retrieved by another consumer. Once the retrieval code has finished processing, it calls Complete on the message. This notifies the service bus that this message is completed and can be permanently removed from the queue. Likewise, if something goes wrong during the processing and an exception is thrown, then the code calls Abandon on the message, notifying the service bus that the message could not be processed and it can be retrieved by another consumer.
Reference -
Get started with Service Bus Queues.
Using Service Bus Topics
Creating Service Bus Topic
- Open Visual Studio and create new console application.
- Add NuGet Packages for Service Bus. And configure the “Microsoft.ServiceBus.ConnectionString” as we did in previous application.
- Write below code in program.cs file.
- string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
-
- var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
-
- if (!namespaceManager.TopicExists("azservicetopic"))
- {
- namespaceManager.CreateTopic("azservicetopic");
- }
Creating a subscription with the default (MatchAll) filter
The MatchAll filter is the default filter that is used if no filter is specified when a new subscription is created.
- string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
-
- var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
-
- if (!namespaceManager.SubscriptionExists("azservicetopic", "AllMessages"))
- {
- namespaceManager.CreateSubscription("azservicetopic", "AllMessages");
- }
Creating subscriptions with filters
The following example creates a subscription named
HighProperty with a
SqlFilter object that only selects messages that have a custom MessageNumber property greater than 3.
- SqlFilter highMessagesFilter =new SqlFilter("MessageNumber> 3");
-
- namespaceManager.CreateSubscription("azservicetopic","HighProperty",highMessagesFilter);
Send messages to a topic
- TopicClient Client = TopicClient.CreateFromConnectionString(connectionString, "azservicetopic");
-
- BrokeredMessage message = newBrokeredMessage("This is sample message ");
- Client.Send(message);
We can also add custom property to
BroderdMessage object.
You can get example in sample code.
Receive messages from a subscription
- SubscriptionClient Client = SubscriptionClient.CreateFromConnectionString(connectionString, "azservicetopic", "HighProperty");
-
- OnMessageOptions options = new OnMessageOptions();
- options.AutoComplete = false;
- options.AutoRenewTimeout = TimeSpan.FromMinutes(1);
- Client.OnMessage((message) =>
- {
- try
- {
-
- Console.WriteLine("High Property Messages");
- Console.WriteLine("Message: " + message.GetBody < string > ());
- Console.WriteLine("Message Number: " +
- message.Properties["MessageNumber"]);
-
- message.Complete();
- }
- catch (Exception)
- {
-
- message.Abandon();
- }
- }, options);
- }