简体   繁体   中英

C# MQ Api How to fetch message without getting exception in case of empty queue

I have to periodically check messages in a queue within Websphere MQ. I haven't found better approach rather than try getting a message and handle 2033 reason code (which is NO_MSG_AVAILABLE) like this:

try
{
    // ...
    inQueue.Get(message);
}
catch (MQException exception)
{
    if (exception.ReasonCode != 2033)
        throw;
}

Is there better way to get message from queue? I think that there might be some openOptions flag that I'm not aware of, that wouldn't throw exception when no message available, but return null instead.

There are three ways to avoid or reduce this polling mechanism. Here they are in oder of elegance(the higher the better):

  1. MQGET with wait interval UNLIMITED and MQGMO_FAIL_IF_QUIESCING
  2. Get your application be triggered by MQServer
  3. Callback function - new with MQ V7 on both sides

You are missing the MQC.MQGMO_WAIT flag on MQGetMessageOptions.Options . Change it this way:

getOptions = new MQGetMessageOptions {WaitInterval = MQC.MQWI_UNLIMITED, Options = MQC.MQGMO_WAIT | MQC.MQGMO_FAIL_IF_QUIESCING}

Please note that this would make the calling thread to be blocked till a message arrives at the queue or some connection exception occurs. MQ has another client called IBM Message Service Client (aka XMS .NET) that provides a JMS specification implementation in .NET. This has a nice little Message Listener which gets automatically invoked whenever a message arrives in a queue. Unlike in the above example, the calling thread will not be blocked when Message Listener is used.

More details on XMS .NET can be found here . Samples are also shipped with MQ and for message listener sample, please refer "SampleAsyncConsumer.cs" source file.

I was getting this. I solved it by putting the Message initiator inside the loop:

_queueManager = new MQQueueManager(Queuemanager, _mqProperties);

MQQueue queue = _queueManager.AccessQueue(
    Queuename, 
    MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING + MQC.MQOO_INQUIRE);            

string xml = "";

while (queue.CurrentDepth > 0)
{
    MQMessage message = new MQMessage();                
    queue.Get(message);
    xml = message.ReadString(message.MessageLength);
    MsgQueue.Enqueue(xml);                    
    message.ClearMessage();                                
}

There must be something in the Message internally that errors when reusing it for another get.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM