Search

6.2. Directly Instantiating JMS Resources Without Using JNDI

download PDF
It is a very common usage pattern to look up JMS Administered Objects (that is JMS queue, topic and ConnectionFactory instances) from JNDI. However in some cases, a JNDI server is not available, and using JMS is still required, or it is preferable to directly instantiate objects. This is possible with HornetQ, which supports the direct instantiation of JMS queue, topic and ConnectionFactory instances.
The following is a simple example, which does not use JNDI at all:
Create the JMS ConnectionFactory object via the HornetQJMSClient Utility class. Note you need to provide connection parameters and specify which transport you are using. For more information on connectors refer to Chapter 14, Configuring the Transport.
TransportConfiguration transportConfiguration =
   new TransportConfiguration(NettyConnectorFactory.class.getName());                
ConnectionFactory cf =
   HornetQJMSClient.createConnectionFactory(transportConfiguration);
Also create the JMS Queue object via the HornetQJMSClient Utility class:
Queue orderQueue = HornetQJMSClient.createQueue("OrderQueue");
Next create a JMS connection using the connection factory:
Connection connection = cf.createConnection();
Create a non transacted JMS Session, with AUTO_ACKNOWLEDGE acknowledge mode:
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Create a MessageProducer that will send orders to the queue:
MessageProducer producer = session.createProducer(orderQueue);
Create a MessageConsumer which will consume orders from the queue:
MessageConsumer consumer = session.createConsumer(orderQueue);
Make sure you start the connection, or delivery will not occur on it:
connection.start();
Create a simple TextMessage and send it:
TextMessage message = session.createTextMessage("This is an order");
producer.send(message);
And we consume the message:
TextMessage receivedMessage = (TextMessage)consumer.receive();
System.out.println("Got order: " + receivedMessage.getText());
Red Hat logoGithubRedditYoutubeTwitter

Learn

Try, buy, & sell

Communities

About Red Hat Documentation

We help Red Hat users innovate and achieve their goals with our products and services with content they can trust.

Making open source more inclusive

Red Hat is committed to replacing problematic language in our code, documentation, and web properties. For more details, see the Red Hat Blog.

About Red Hat

We deliver hardened solutions that make it easier for enterprises to work across platforms and environments, from the core datacenter to the network edge.

© 2024 Red Hat, Inc.