我們在升級一個POS系統的時候,決定使用微軟公有雲計算平台下的Azure ServiceBus 進行POS客戶端與服務器的交互。
本文主要時作者在學習使用 Azure SDK for .NET 操作由世紀互聯運營的 中國區Azure 上的 Service Bus。
目錄
一、安裝AzureServiceBus程序集
二、在Portal創建命名空間
三、通過代碼創建Topic
四、通過代碼創建訂閱
五、創建並發送消息
六、消費消息
1.通過nuget安裝程序集
using Microsoft.ServiceBus;
using Microsoft.ServiceBus.Messaging;
using Microsoft.Azure;
2. 在Portal創建 service bus 命名空間:
只有標准級別可以使用主題(Topic),因此創建命名空間時,請選擇標准;
也可以創建后,在縮放選項卡里調整為標准。
3.創建主題,可以通過portal創建,也可以通過代碼創建:
通過代碼創建主題:

1 // Create the topic if it does not exist already. 2 string connectionString = 3 CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString"); 4 5 var namespaceManager = 6 NamespaceManager.CreateFromConnectionString(connectionString); 7 8 if (!namespaceManager.TopicExists("TestTopic")) 9 { 10 11 //默認的createtopic方法 12 namespaceManager.CreateTopic("TestTopic"); 13 14 15 // 通過TopicDescription構建一個重載 16 //TopicDescription td = new TopicDescription("TestTopicCustomer"); 17 //td.MaxSizeInMegabytes = 5120; 18 //td.DefaultMessageTimeToLive = new TimeSpan(0, 1, 0); 19 //if (!namespaceManager.TopicExists("TestTopicCustomer")) 20 //{ 21 // namespaceManager.CreateTopic(td); 22 //} 23 24 }
4.創建訂閱:
下面的代碼演示創建了三個訂閱,其中Product和Customer訂閱增加了一個SqlFilter,即如果發送消息時,
message.Properties["Entity"] = "Product",則消息會由Product訂閱處理;
message.Properties["Entity"] = "Customer",則消息會由Customer訂閱處理;

1 string connectionString = 2 CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString"); 3 4 var namespaceManager = 5 NamespaceManager.CreateFromConnectionString(connectionString); 6 7 if (!namespaceManager.SubscriptionExists("TestTopic", "AllMessages")) 8 { 9 namespaceManager.CreateSubscription("TestTopic", "AllMessages"); 10 } 11 12 Console.WriteLine("AllMessages done"); 13 14 15 // Create a "ProductMessagesFilter" filtered subscription. 16 SqlFilter ProductMessagesFilter = 17 new SqlFilter("Entity='Product'"); 18 19 namespaceManager.CreateSubscription("TestTopic", 20 "Product", 21 ProductMessagesFilter); 22 23 Console.WriteLine("Product done"); 24 25 // Create a "CustomerMessagesFilter" filtered subscription. 26 SqlFilter CustomerMessagesFilter = 27 new SqlFilter("Entity='Customer'"); 28 29 namespaceManager.CreateSubscription("TestTopic", 30 "Customer", 31 CustomerMessagesFilter); 32 33 Console.WriteLine("Customers done");
5.創建並發送普通消息:
下面創建了5個product和3個customer並發送了消息,
BrokeredMessage message = new BrokeredMessage(product);
BrokeredMessage message = new BrokeredMessage(customer);
Product有如下設置:message.Properties["Entity"] = "Product";
Customer有如下設置:message.Properties["Entity"] = "Customer";
則 product 訂閱會有5條消息,customer訂閱會有3條消息,另外,Allmessages沒有任何sqlfilter,則該訂閱會有5+3=8條消息。

1 string connectionString = 2 CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString"); 3 4 TopicClient Client = 5 TopicClient.CreateFromConnectionString(connectionString, "TestTopic"); 6 7 // Client.Send(new BrokeredMessage()); 8 9 10 //Add 5 Products 11 var product = new Model.Product(); 12 13 for (int i = 0; i < 5; i++) 14 { 15 16 product.ProductID ="ProductID"+ i.ToString(); 17 18 // Create message, passing a Product for the body. 19 BrokeredMessage message = new BrokeredMessage(product); 20 21 // Set additional custom app-specific property. 22 message.Properties["Entity"] = "Product"; 23 24 //ScheduledMessage 25 //message.ScheduledEnqueueTimeUtc = DateTime.Now.AddMinutes(1); 26 27 // Send message to the topic. 28 Client.Send(message); 29 } 30 31 32 //Add 3 Customers 33 var customer = new Model.Customer(); 34 35 for (int i = 0; i < 3; i++) 36 { 37 38 customer.CustomerID = "CustomerID"+i.ToString(); 39 40 // Create message, passing a Customer message for the body. 41 BrokeredMessage message = new BrokeredMessage(customer); 42 43 // Set additional custom app-specific property. 44 message.Properties["Entity"] = "Customer"; 45 46 // Send message to the topic. 47 Client.Send(message); 48 }
發送消息后的效果:
創建定時消息:
設置消息的如下屬性,則消息在發送成功后延時1分鍾后才會出現在上圖中,也才可以被訂閱消費。
message.ScheduledEnqueueTimeUtc = DateTime.Now.AddMinutes(1);
6.消費消息:
不同的訂閱可以取不同訂閱里的消息進行處理,處理完成后,標記message.Complete()即可從訂閱里清除消息。

1 string connectionString = 2 CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString"); 3 4 //SubscriptionClient Client = 5 // SubscriptionClient.CreateFromConnectionString 6 // (connectionString, "TestTopic", "Customer"); 7 8 //SubscriptionClient Client = 9 // SubscriptionClient.CreateFromConnectionString 10 // (connectionString, "TestTopic", "Product"); 11 12 SubscriptionClient Client = 13 SubscriptionClient.CreateFromConnectionString 14 (connectionString, "TestTopic", "AllMessages"); 15 16 // Configure the callback options. 17 OnMessageOptions options = new OnMessageOptions(); 18 options.AutoComplete = false; 19 options.AutoRenewTimeout = TimeSpan.FromMinutes(1); 20 21 Client.OnMessage((message) => 22 { 23 try 24 { 25 // Process message from subscription. 26 Console.WriteLine("Messages"); 27 28 Console.WriteLine("MessageID: " + message.MessageId); 29 Console.WriteLine("Message EntityType=: " + 30 message.Properties["Entity"]); 31 32 33 if(message.Properties["Entity"].ToString()=="Customer") 34 { 35 Console.WriteLine("CustomerID=" + message.GetBody<Customer>().CustomerID.ToString()); 36 } 37 if (message.Properties["Entity"].ToString() == "Product") 38 { 39 Console.WriteLine("ProductID=" + message.GetBody<Product>().ProductID.ToString()); 40 } 41 42 43 44 // Remove message from subscription. 45 message.Complete(); 46 } 47 catch (Exception) 48 { 49 // Indicates a problem, unlock message in subscription. 50 message.Abandon(); 51 } 52 }, options); 53 54 Console.ReadLine();
特別注意:消費掉Product或Customer里的消息后,AllMessage里的消息不受影響。