IBM MQ 提供了一种浏览消息的方法,而无需将它们从队列中移除。您可以从头开始浏览消息并遍历队列中的所有消息。您还可以使用 MessageId 或 CorrelationId 浏览特定消息。
这是 C# 中用于浏览队列中消息的片段。
/// <summary>
/// Browse messages in a queue
/// </summary>
private void BrowseMessages()
{
MQQueueManager qm = null;
MQQueue queueGet = null;
Hashtable mqProps = null;
try
{
mqProps = new Hashtable();
// Setup properties for connection
mqProps.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_MANAGED);
mqProps.Add(MQC.HOST_NAME_PROPERTY, "localhost");
mqProps.Add(MQC.PORT_PROPERTY, 1414);
mqProps.Add(MQC.CHANNEL_PROPERTY, "QM.SVRCONN");
// Open connection to queue manager
qm = new MQQueueManager("QM", mqProps);
// Open queue for browsing
queueGet = qm.AccessQueue("Q1", MQC.MQOO_BROWSE | MQC.MQOO_FAIL_IF_QUIESCING);
// In a loop browse all messages till we reach end of queue
while (true)
{
try
{
// Need to create objects everytime
MQMessage msg = new MQMessage();
MQGetMessageOptions gmo = new MQGetMessageOptions();
// Use browse next option to start browsing
gmo.Options = MQC.MQGMO_BROWSE_NEXT;
queueGet.Get(msg, gmo);
Console.WriteLine(msg.ReadString(msg.MessageLength));
}
catch (MQException mqex)
{
// When there are no more messages to browse, the Get call
// will throw MQException with reason code MQC.MQRC_NO_MSG_AVAILABLE.
// But here we close the queue and break out of loop for all exceptions
queueGet.Close();
break;
}
}
qm.Disconnect();
}
catch (MQException mqex)
{
Console.WriteLine(mqex);
}
}