我正在連接到IBM Websphere MQ。我希望能夠將回復消息與正確的請求消息進行匹配。我瀏覽了數百頁來獲得這個,並沒有運氣。如何將MQ服務器回覆消息與正確請求匹配
我有一個類 - MQHandler - 它發送消息到一個定義的隊列,並從另一個讀取請求。這很好,但是,如果多個用戶同時使用該應用程序,則消息會混淆在一起。
我似乎無法得到接收方指示CorrelationID匹配的方法。 類似...
consumer.receive(selector);
你能檢查下面的方法以確保我正確地做到了這一點嗎?
/**
* When the class is called, this initialisation is done first.
*
* @throws JMSException
*/
public void init() throws JMSException
{
// Create a connection factory
JmsFactoryFactory ff;
try
{
ff = JmsFactoryFactory.getInstance(WMQConstants.WMQ_PROVIDER);
cf = ff.createConnectionFactory();
// Set the properties
cf.setStringProperty(WMQConstants.WMQ_HOST_NAME, hostServer);
cf.setIntProperty(WMQConstants.WMQ_PORT, 1414);
cf.setStringProperty(WMQConstants.WMQ_CHANNEL, channel);
cf.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE, WMQConstants.WMQ_CM_CLIENT);
cf.setStringProperty(WMQConstants.WMQ_QUEUE_MANAGER, qManager);
connection = cf.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
}
catch(JMSException e)
{
throw e;
}
} // end of init
/**
* @param request
* @return
* @throws JMSException
*/
private String sendRequest(String request) throws JMSException
{
// Create JMS objects
Destination destination = session.createQueue("queue:///" + writeQueueName);
// Enable write of MQMD fields. See documentation for further
// details.
((JmsDestination) destination).setBooleanProperty(WMQConstants.WMQ_MQMD_WRITE_ENABLED, true);
// Set message context, if needed. See comment at the top.
// Create a producer
MessageProducer producer = session.createProducer(destination);
// Create a message
TextMessage message = session.createTextMessage(request);
// Generate a custom message id
message.setJMSCorrelationID(generateRandomID());
// Start the connection
connection.start();
// And, send the message
producer.send(message);
System.out.println(message);
return message.getJMSCorrelationID();
}
/**
* @param customMessageId
* @return
* @throws JMSException
*/
private String recvResponse(String customMessageId) throws JMSException
{
Destination destination = session.createQueue("queue:///" + readQueueName);
// Enable read of MQMD fields.
((JmsDestination) destination).setBooleanProperty(WMQConstants.WMQ_MQMD_READ_ENABLED, true);
((JmsDestination) destination).setObjectProperty(WMQConstants.JMS_IBM_MQMD_CORRELID, customMessageId);
// Create a consumer
MessageConsumer consumer = session.createConsumer(destination);
// Start the connection
connection.start();
// And, receive a message from the queue
TextMessage receivedMessage = (TextMessage)consumer.receive(15000);
connection.close();
session.close();
return receivedMessage.getText();
}
下面是主要方法的一個片段:
try
{
String customMessageId;
init();
customMessageId = sendRequest(request);
return recvResponse(customMessageId);
}
catch(Exception ex)
{
System.out.println("Error on MQ.");
throw new Exception("\n\n*** An error occurred ***\n\n" + ex.getLocalizedMessage()
+ "\n\n**********************************");
}