我们在升级一个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创建,也可以通过代码创建:

通过代码创建主题:

 // Create the topic if it does not exist already.
string connectionString =
CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString"); var namespaceManager =
NamespaceManager.CreateFromConnectionString(connectionString); if (!namespaceManager.TopicExists("TestTopic"))
{ //默认的createtopic方法
namespaceManager.CreateTopic("TestTopic"); // 通过TopicDescription构建一个重载
//TopicDescription td = new TopicDescription("TestTopicCustomer");
//td.MaxSizeInMegabytes = 5120;
//td.DefaultMessageTimeToLive = new TimeSpan(0, 1, 0);
//if (!namespaceManager.TopicExists("TestTopicCustomer"))
//{
// namespaceManager.CreateTopic(td);
//} }

4.创建订阅:

下面的代码演示创建了三个订阅,其中Product和Customer订阅增加了一个SqlFilter,即如果发送消息时,

message.Properties["Entity"] = "Product",则消息会由Product订阅处理;

message.Properties["Entity"] = "Customer",则消息会由Customer订阅处理;

  string connectionString =
CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString"); var namespaceManager =
NamespaceManager.CreateFromConnectionString(connectionString); if (!namespaceManager.SubscriptionExists("TestTopic", "AllMessages"))
{
namespaceManager.CreateSubscription("TestTopic", "AllMessages");
} Console.WriteLine("AllMessages done"); // Create a "ProductMessagesFilter" filtered subscription.
SqlFilter ProductMessagesFilter =
new SqlFilter("Entity='Product'"); namespaceManager.CreateSubscription("TestTopic",
"Product",
ProductMessagesFilter); Console.WriteLine("Product done"); // Create a "CustomerMessagesFilter" filtered subscription.
SqlFilter CustomerMessagesFilter =
new SqlFilter("Entity='Customer'"); namespaceManager.CreateSubscription("TestTopic",
"Customer",
CustomerMessagesFilter); 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条消息。

  string connectionString =
CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString"); TopicClient Client =
TopicClient.CreateFromConnectionString(connectionString, "TestTopic"); // Client.Send(new BrokeredMessage()); //Add 5 Products
var product = new Model.Product(); for (int i = ; i < ; i++)
{ product.ProductID ="ProductID"+ i.ToString(); // Create message, passing a Product for the body.
BrokeredMessage message = new BrokeredMessage(product); // Set additional custom app-specific property.
message.Properties["Entity"] = "Product"; //ScheduledMessage
//message.ScheduledEnqueueTimeUtc = DateTime.Now.AddMinutes(1); // Send message to the topic.
Client.Send(message);
} //Add 3 Customers
var customer = new Model.Customer(); for (int i = ; i < ; i++)
{ customer.CustomerID = "CustomerID"+i.ToString(); // Create message, passing a Customer message for the body.
BrokeredMessage message = new BrokeredMessage(customer); // Set additional custom app-specific property.
message.Properties["Entity"] = "Customer"; // Send message to the topic.
Client.Send(message);
}

发送消息后的效果:

创建定时消息:

设置消息的如下属性,则消息在发送成功后延时1分钟后才会出现在上图中,也才可以被订阅消费。

message.ScheduledEnqueueTimeUtc = DateTime.Now.AddMinutes(1);

6.消费消息:

不同的订阅可以取不同订阅里的消息进行处理,处理完成后,标记message.Complete()即可从订阅里清除消息。

 string connectionString =
CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString"); //SubscriptionClient Client =
// SubscriptionClient.CreateFromConnectionString
// (connectionString, "TestTopic", "Customer"); //SubscriptionClient Client =
// SubscriptionClient.CreateFromConnectionString
// (connectionString, "TestTopic", "Product"); SubscriptionClient Client =
SubscriptionClient.CreateFromConnectionString
(connectionString, "TestTopic", "AllMessages"); // Configure the callback options.
OnMessageOptions options = new OnMessageOptions();
options.AutoComplete = false;
options.AutoRenewTimeout = TimeSpan.FromMinutes(); Client.OnMessage((message) =>
{
try
{
// Process message from subscription.
Console.WriteLine("Messages"); Console.WriteLine("MessageID: " + message.MessageId);
Console.WriteLine("Message EntityType=: " +
message.Properties["Entity"]); if(message.Properties["Entity"].ToString()=="Customer")
{
Console.WriteLine("CustomerID=" + message.GetBody<Customer>().CustomerID.ToString());
}
if (message.Properties["Entity"].ToString() == "Product")
{
Console.WriteLine("ProductID=" + message.GetBody<Product>().ProductID.ToString());
} // Remove message from subscription.
message.Complete();
}
catch (Exception)
{
// Indicates a problem, unlock message in subscription.
message.Abandon();
}
}, options); Console.ReadLine();

特别注意:消费掉Product或Customer里的消息后,AllMessage里的消息不受影响。

Azure service bus Topic基本用法的更多相关文章

  1. Windows Azure Service Bus (5) 主题(Topic) 使用VS2013开发Service Bus Topic

    <Windows Azure Platform 系列文章目录> 项目文件,请在这里下载 在笔者之前的文章中Windows Azure Service Bus (1) 基础 介绍了Servi ...

  2. Windows Azure Service Bus Topics实现系统松散耦合

    前言 Windows Azure中的服务总线(Service Bus)提供了多种功能, 包括队列(Queue), 主题(Topic),中继(Relay),和通知中心(Notification Hub) ...

  3. Windows Azure Service Bus (4) Service Bus Queue和Storage Queue的区别

    <Windows Azure Platform 系列文章目录> 熟悉笔者文章的读者都了解,Azure提供两种不同方式的Queue消息队列: 1.Azure Storage Queue 具体 ...

  4. 阿里云ONS而微软Azure Service Bus体系结构和功能比较

    阿里云ONS而微软Azure Service bus体系结构和功能比较 版权所有所有,转载请注明出处http://blog.csdn.net/yangzhenping.谢谢! 阿里云的开放消息服务: ...

  5. 如何在ASP.NET Core中使用Azure Service Bus Queue

    原文:USING AZURE SERVICE BUS QUEUES WITH ASP.NET CORE SERVICES 作者:damienbod 译文:如何在ASP.NET Core中使用Azure ...

  6. 使用Service Bus Topic 实现简单的聊天室

    创建Service Bus能够參照: https://azure.microsoft.com/en-gb/documentation/articles/service-bus-dotnet-how-t ...

  7. 【Azure 服务总线】详解Azure Service Bus SDK中接收消息时设置的maxConcurrentCalls,prefetchCount参数

    (Azure Service Bus服务总线的两大类消息处理方式: 队列Queue和主题Topic) 问题描述 使用Service Bus作为企业消息代理,当有大量的数据堆积再Queue或Topic中 ...

  8. Azure Service Bus 中的身份验证方式 Shared Access Signature

    var appInsights=window.appInsights||function(config){ function r(config){t[config]=function(){var i= ...

  9. Windows Azure Service Bus Notification Hub推送通知

    前言 随着Windows Azure 在中国的正式落地,相信越来越多的人会体验到Windows Azure带来的强大和便利.在上一篇文章中, 我们介绍了如何利用Windows Azure中的Servi ...

随机推荐

  1. String StringBuffer StringBuilder 三者之间的区别

    今天被公司骗去面试,好糟心...... 这个问题不管去哪里面试,基础问题基本上都会问到这个问题.网上好多大神都总结,这里自己也总结一下. 首先我们最开始学的就是String字符串常量,这里有行代码 S ...

  2. Django_model基础

    Django-model基础   ORM 映射关系: 表名 <-------> 类名 字段 <-------> 属性 表记录 <------->类实例对象 创建表( ...

  3. 多线程设计模式(一) Single Threaded Execution

    这里有一座独木桥.因为桥身非常的细,一次只能允许一个人通过.当这个人没有下桥,另一个人就不能过桥.如果桥上同时又两个人,桥就会因为无法承重而破碎而掉落河里. 这就是Single Threaded Ex ...

  4. Xamarin.Forms初始

    前言 Xamarin.Forms 为 .NET 开发人员提供一个完整的跨平台 UI 工具包. 在 Visual Studio 中使用 C# 生成完全本机的 Android.iOS 和通用 Window ...

  5. Rsyslog 日志相关内容

    [root@server vusers_home]# rpm -ql rsyslog|more       ###.so结尾为模块,模块有分im为输入模块,om 为输出模块/etc/logrotate ...

  6. 「LuoguP3808」 【模板】AC自动机(简单版)

    题目背景 通过套取数据而直接“打表”过题者,是作弊行为,发现即棕名. 这是一道简单的AC自动机模板题. 用于检测正确性以及算法常数. 为了防止卡OJ,在保证正确的基础上只有两组数据,请不要恶意提交. ...

  7. 解决Exception:Could not open Hibernate Session for transaction; nested exception is java.lang.NoClassDefFoundError: org/hibernate/engine/transaction/spi/TransactionContext

    原因是配置文件中 <bean id="transactionManager" class="org.springframework.orm.hibernate4.H ...

  8. tyvj1940创世纪——贪心(基环树)

    题目:http://www.joyoi.cn/problem/tyvj-1940 基环树的样子,看了书上的讲解,准备写树上DP,然后挂了: #include<iostream> #incl ...

  9. Keil BUG 导致读字库时,无法显示某些汉字解决办法

    原因在于:KEIL C51 的一个汉字BUG,keil c51在编译的时候会将0xfd的字符(有些汉字含该字符的内码)过滤, 最佳解决方案:打补丁,用  晓奇工作室出的补丁 cckeilvxx.exe ...

  10. bzoj3569

    线性基 非常高端 强制在线动态图 我们先搞出一个dfs树,然后所有非树边都和树边形成一个环.我们考虑什么情况会不连通,当且仅当树边和dfs序大于当前点的返祖边都被断掉才不连通,那么我们给每个非树边赋一 ...