JMS: How to block several connections from one client to one broker


I had the problem, that it should not be allowed to run 2 instances of the client simultaneously with the same broker.

I fixed that issue by setting the JMS Property ClientID.
When connecting to the broker, you can set a clientID. This ID is then registered on the Broker. If you now run that tool again (while the first instance is still running), then the second instance tries to connect, but the broker does not allow a second instance with the same clientID.


Code Example:

// Create a JNDI API InitialContext object
Properties props = new Properties();
props.setProperty(Context.PROVIDER_URL, server);

jndiContext = new InitialContext(props);
connectionFactory = (ConnectionFactory) jndiContext.lookup("ConnectionFactory");
requestQueue = (Destination) jndiContext.lookup("dynamicQueues/" + requestQueueName);
responseQueue = (Destination) jndiContext.lookup("dynamicQueues/"+ responseQueueName);

//Connect to  ActiveMQ
connection = connectionFactory.createConnection();
// this helps to ensure, that not 2 instances can connect to the broker simultaneously
// because it is not allowed to connect to the same broker with the same clientID
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);