IBM MQ extends API support for Java developers to work with MQ in their applications. In this article we will see how we can put messages to the local queue and browse them back using Java.
Connecting to a queue manager
In order to manipulate a message queue first we should connect to a local queue manager using MQQueueManager class.
MQQueueManager qMgr = new MQQueueManager (queue manager name as a string);
- This step is optional if you want to communicate with the default queue manager
Opening the queue
A queue can be opened for various purposes such as put, browse, inquire etc. We specify our purpose of opening the queue by specifying Open Options.
Queue open options
Opens the destination queue to put messages
Opens the queue to get messages with exclusive access. If the queue is already in use, the call will fail.
Opens the queue if it is already opened by some other application for retrieving messages.
Used to inquire queue attributes such as queue depth
Opens queue with default queue attribute.
Opens the queue to browse messages.
In order to communicate with any queue, we need to supply queue name and open options along with it to the queue manager.
Example code snippet to open a queue
int openOptions = MQConstants.MQOO_INPUT_AS_Q_DEF | MQConstants.MQOO_OUTPUT;
MQQueue queue = qMgr.accessQueue(queue name as a string, openOptions);
Construct and put a message into queue
Create an instance of MQMessage class, call writeString/wtriteUTF etc., supply your message as a string argument. That constructs a message.
To put message into queue we need to pass our message and put message options as parameters to put method of MQQueue instance.
Closing the queue
Closing the queue after manipulating it is always a best practice. We should use close() method of MQQueue class to close a queue.
MQQueueManager qManager = new MQQueueManager ("queue manager name");
int openOptions = MQConstants.MQOO_INPUT_AS_Q_DEF|MQConstants.MQOO_OUTPUT;
MQQueue queue = qMgr.accessQueue(“queue name", openOptions);
MQMessage msg = new MQMessage();
MQPutMessageOptions pmo = new MQPutMessageOptions();
queue.closeOptions = this.closeOptions;