Handling messages in WebSphere MQ classes for Java
Messages are represented by the MQMessage class. You put and get messages using methods of the MQDestination class, which has subclasses of MQQueue and MQTopic.
Put messages onto queues or topics using the put() method of the MQDestination class. You get messages from queues or topics using the get() method of the MQDestination class. Unlike the procedural interface, where MQPUT and MQGET put and get arrays of bytes, the Java programming language puts and gets instances of the MQMessage class. The MQMessage class encapsulates the data buffer that contains the actual message data, together with all the MQMD (message descriptor) parameters and message properties that describe that message.
To build a new message, create a new instance of the MQMessage class, and use the writeXXX methods to put data into the message buffer.
// Build a new message containing my age followed by my name
MQMessage myMessage = new MQMessage();
myMessage.writeInt(25);
String name = "Charlie Jordan";
myMessage.writeInt(name.length());
myMessage.writeBytes(name);
// Use the default put message options...
MQPutMessageOptions pmo = new MQPutMessageOptions();
// put the message!
queue.put(myMessage,pmo);
The get() method of MQDestination returns a new instance
of MQMessage, which represents the message just taken from the queue.
It also takes an instance of the MQGetMessageOptions class as a parameter.
This class represents the MQGMO structure.You do not need to specify a maximum message size, because the get() method automatically adjusts the size of its internal buffer to fit the incoming message. Use the readXXX methods of the MQMessage class to access the data in the returned message.
// Get a message from the queue
MQMessage theMessage = new MQMessage();
MQGetMessageOptions gmo = new MQGetMessageOptions();
queue.get(theMessage,gmo); // has default values
// Extract the message data
int age = theMessage.readInt();
int strLen = theMessage.readInt();
byte[] strData = new byte[strLen];
theMessage.readFully(strData,0,strLen);
String name = new String(strData,0);
You can alter the number format that the read and write methods use by setting the encoding member variable.
You can alter the character set to use for reading and writing strings by setting the characterSet member variable.
See MQMessage class for more information.