I am using JMS to put messages into the Queue.
The Queue is linked with 2 QueueConnection Factories and 2 Queue managers. While sending the messages to the Queue I want to equally distribute/send message to 2 different Queue Managers via 2 different Queue Connection factory.
Example:
In different point of time, My service receives messages from some user.I need to equally put the messages into 2 QCF/QueueManagers.(load balancing)
If I get 1st message I need to send to 1st QCF1/Queue Manager and If another msg arrives to my service I will have to send it to 2nd QCF1/Queue Manager.
Because JMS allows me to create Queue Coontion with yhe help of onle 1 QCF at a time.
Can this be accomplished using JMS? Or anyother way to achieve this?
Approach to send message to Queue using one QCF:
import javax.naming.InitialContext;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.QueueSession;
import javax.jms.QueueSender;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
public class Receiver
{
@Resource(lookup = "jms/ConnectionFactory1")
private static QueueConnectionFactory connectionFactory1;
@Resource(lookup = "jms/ConnectionFactory2")
private static QueueConnectionFactory connectionFactory2;
@Resource(lookup = "jms/Queue")
private static Queue queue;
public void readQueueMessages() {
try {
// create a queue connection
QueueConnection queueConn = connectionFactory1.createQueueConnection();
// create a queue session
QueueSession queueSession = queueConn.createQueueSession(true, 0);
// create a queue receiver
QueueSender queueSender = queueSession.createSender(queue);
TextMessage msg = queueSession.createTextMessage();
// start the connection
queueConn.start();
msg.setText("Hi");
queueSender.send(msg);
queueSender.close();
queueSession.close();
queueConn.close();
}
} catch(JMSException exp) {
// Handle this exception
} finally {
if(queueConn != null) {
// close the queue connection
queueConn.close();
}
}
}
}
Since you mention about load balancing, it would be better to use IBM MQ queue manager clustering instead of using your own code to distribute messages. You will need to put the queue managers in a MQ cluster and define an instance of cluster queue in QM1 and QM2, something like below.
When a message destined to CLUSQ1 arrives on QM Gateway, the queue manager will route the message to other queue manager in the cluster using default round robin method.
Read here for more on MQ Clustering