关于ActiveMQ在C#中的应用,https://blog.csdn.net/bodybo/article/details/5647968这篇文章已经有介绍,但是这篇文章介绍的是ActiveMQ推送消息的模式,我碰到的场景是当前分布式节点从消息队列中读取任务,并在当前节点开启多线程进行处理。如果在本地进行缓存,则不利于负载均衡,且服务器宕机会造成任务丢失,所以我采用了主动从消息队列读取的方式来获取任务,其他代码均相同,但是不调用listener事件,代码如下:
private void consumer_thread()
{
IConnectionFactory factory = new ConnectionFactory("tcp://localhost:61616/");
IConnection connection = factory.CreateConnection();
connection.ClientId = "testing listener";
connection.Start();
ISession session = connection.CreateSession();
IMessageConsumer consumer = session.CreateConsumer(new Apache.NMS.ActiveMQ.Commands.ActiveMQQueue("testing"), "myFilter='test1'");
while (true)
{
var msg = consumer.Receive(TimeSpan.FromSeconds(3));
if (msg != null)
{
var message = msg as ITextMessage;
Console.WriteLine(message.Text);
}
}
}