读取ActiveMQ消息而不删除

时间:2011-11-09 15:49:51

标签: c# activemq nms

我正在尝试阅读ActiveMQ消息并根据某些过滤器处理其中一些消息或将其他消息留在队列中。 我使用NMS API和以下代码:

        Uri connecturi = new Uri("activemq:tcp://model.net:61616");
        IConnectionFactory factory = new NMSConnectionFactory(connecturi);
        List<ModelBuilderBase> result = new List<ModelBuilderBase>();
        using (IConnection connection = factory.CreateConnection())
        using (ISession session = connection.CreateSession())
        {
            IDestination destination = SessionUtil.GetDestination(session, "queue://cidModelbuilderQ");
            using (IMessageConsumer consumer = session.CreateConsumer(destination))
            {
                connection.Start();
                ITextMessage message;
                while ((message = consumer.ReceiveNoWait() as ITextMessage) != null)
                {
                    if (message.Properties[MANDATOR] == null || message.Properties[REFCODE] == null)
                        continue;
                    var mandator = message.Properties[MANDATOR].ToString();
                    var refCode = message.Properties[REFCODE].ToString();
                    result.Add(ModelBuilderFactory.Instance.GetInstance(refCode, mandator));
                }
            }

问题是收到消息后消息被删除。我可以以某种方式更改此行为并仅在成功处理后手动删除消息吗?             }

2 个答案:

答案 0 :(得分:4)

创建QueueBrowser对象以查看指定队列上的消息。对消息执行逻辑,然后创建QueueReceiver对象以接收来自指定队列的消息。

答案 1 :(得分:4)

虽然为此编写一个有效的代码并不容易,但由于ARS的回答,我现在有了这个有效的解决方案:

        Uri connecturi = new Uri("activemq:tcp://model.net:61616");
        IConnectionFactory factory = new NMSConnectionFactory(connecturi);
        List<ModelBuilderBase> result = new List<ModelBuilderBase>();
        using (IConnection connection = factory.CreateConnection())
        using (ISession session = connection.CreateSession())
        {

            IDestination destination = SessionUtil.GetDestination(session, "queue://cidModelbuilderQ");
            using (IMessageConsumer consumer = session.CreateConsumer(destination))
            {
                connection.Start();
                var q = session.GetQueue("cidModelbuilderQ");
                var b = session.CreateBrowser(q);
                var msgs = b.GetEnumerator();
                while (msgs.MoveNext())
                {
                    ITextMessage message = msgs.Current as ITextMessage;
                    if (message.Properties[MANDATOR] == null || message.Properties[REFCODE] == null)
                        continue;
                    var mandator = message.Properties[MANDATOR].ToString();
                    var refCode = message.Properties[REFCODE].ToString();
                    result.Add(ModelBuilderFactory.Instance.GetInstance(refCode, mandator));
                }
            }
        }