ActiveMQ发布订阅模式(转)
2024-10-18 22:35:42
ActiveMQ的另一种模式就SUB/HUB即发布订阅模式,是SUB/hub就是一拖N的USB分线器的意思。意思就是一个来源分到N个出口。还是上节的例子,当一个订单产生后,后台N个系统需要联动,但有一个前提是都需要收到订单信息,那么我们就需要将一个生产者的消息发布到N个消费者。
生产者:
try
{
//Create the Connection Factory
IConnectionFactory factory = new ConnectionFactory("tcp://localhost:61616/");
using (IConnection connection = factory.CreateConnection())
{
//Create the Session
using (ISession session = connection.CreateSession())
{
//Create the Producer for the topic/queue
IMessageProducer prod = session.CreateProducer(
new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic("testing")); //Send Messages
int i = ; while (!Console.KeyAvailable)
{
ITextMessage msg = prod.CreateTextMessage();
msg.Text = i.ToString();
Console.WriteLine("Sending: " + i.ToString());
prod.Send(msg, Apache.NMS.MsgDeliveryMode.NonPersistent, Apache.NMS.MsgPriority.Normal, TimeSpan.MinValue); System.Threading.Thread.Sleep();
i++;
}
}
} Console.ReadLine();
}
catch (System.Exception e)
{
Console.WriteLine("{0}", e.Message);
Console.ReadLine();
}
假设生产者每5秒发送一次消息:
消费者:
static void Main(string[] args)
{
try
{
//Create the Connection factory
IConnectionFactory factory = new ConnectionFactory("tcp://localhost:61616/"); //Create the connection
using (IConnection connection = factory.CreateConnection())
{
connection.ClientId = "testing listener1";
connection.Start(); //Create the Session
using (ISession session = connection.CreateSession())
{
//Create the Consumer
IMessageConsumer consumer = session.CreateDurableConsumer(new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic("testing"), "testing listener1", null, false); consumer.Listener += new MessageListener(consumer_Listener); Console.ReadLine();
}
connection.Stop();
connection.Close();
}
}
catch (System.Exception e)
{
Console.WriteLine(e.Message);
}
} static void consumer_Listener(IMessage message)
{
try
{
ITextMessage msg = (ITextMessage)message;
Console.WriteLine("Receive: " + msg.Text);
}
catch (System.Exception e)
{
Console.WriteLine(e.Message);
}
}
启动一个消费者:
我们发现他是从15开始的,而不是像上节一样从头开始,再启动另一个消费者:
我们发现就是从启动时开始接受消息的,之前的消息就丢失了。
整体状态如下:
我们观察管理界面:
产生了一个testing的Topics,而订阅方有2个都订阅的是testing:
这样只需要在需要获取消息的地方订阅即可及时获得。
最新文章
- Smarty缓存的5个知识点
- Android进程间通信之LocalSocket通信
- HR外包系统 - 工资计算-几种常见账单计算规则
- 一些常用的C++标准函数
- Zabbix通过percona监控MySQL
- [算法]树上倍增求LCA
- Linux高级编程--09.线程互斥与同步
- js 倒计时 button不可用
- POJ 3744 Scout YYF I (概率dp+矩阵快速幂)
- content:attr()
- unity3D插件开发——前篇
- [Sdoi2017]序列计数 [矩阵快速幂]
- WMS二开:外挂页面开发培训
- repository和repertory
- UE4联机编译光照
- English Pronunciation Analysis | Advanced English Conversation
- 【BZOJ1055】[HAOI2008]玩具取名(动态规划)
- jq给单选框 radio添加或删除选中状态
- Linux-文件和目录属性
- 基于Netty4.1.29.Final的helloworld实现.使用idea
热门文章
- DTO学习系列之AutoMapper(五)----当EntityFramework爱上AutoMapper
- WCF入门教程系列四
- 为什么要用Math.sqrt(i)方法
- Mac添加或修改环境变量
- 让footer在底部(测试它人方法)
- 最大公约数(gcd):Euclid算法证明
- pubwin 客户端会员无法自助结账的排查方法
- 小试牛刀——爬topit.me的图片,附github简易上传教程
- LeetCode_N-Queens
- 【转帖】C# DllImport 系统调用使用详解 托管代码的介绍 EntryPoint的使用