HornetQ Stand Alone – Basic JMS Messaging Example

HornetQ is an open source project to build a multi-protocol, embeddable, very high performance, clustered, asynchronous messaging system. HornetQ supports the JMS 1.1 API and also defines its own messaging API for maximum performance and flexibility. HornetQ class-beating high performance journal provides persistent messaging performance at rates normally seen for non-persistent messaging. HornetQ offers server replication and automatic client fail-over to eliminate lost or duplicated messages in case of server failure.

In previous post, we learned about configuring a stand alone hornetq server and basic configuration. Lets take the example forward.

In this post, we will learn the mechanism of sending JMS messages to a queue on hornetq server and then we will retrieve those messages.

Step 1) Create a maven project using below command and convert it to eclipse java project

mvn archetype:generate -DgroupId=com.howtodoinjava -DartifactId=HornetQHelloWorld
-DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

 cd HornetQHelloWorld

 mvn eclipse:eclipse

step 2) Update pom.xml file and update the project dependencies

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.howtodoinjava</groupId>
  <artifactId>HornetQHelloWorld</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>HornetQHelloWorld</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  <dependency>
     <groupId>org.hornetq</groupId>
     <artifactId>hornetq-core</artifactId>
     <version>2.0.0.GA</version>
     <scope>compile</scope>
  </dependency>
  <dependency>
     <groupId>org.hornetq</groupId>
     <artifactId>hornetq-jms</artifactId>
     <version>2.0.0.GA</version>
     <scope>compile</scope>
  </dependency>
  <dependency>
     <groupId>org.hornetq</groupId>
     <artifactId>hornetq-logging</artifactId>
     <version>2.0.0.GA</version>
     <scope>compile</scope>
  </dependency>
  <dependency>
     <groupId>org.hornetq</groupId>
     <artifactId>hornetq-transports</artifactId>
     <version>2.0.0.GA</version>
     <scope>compile</scope>
  </dependency>
  <dependency>
     <groupId>org.jboss.netty</groupId>
     <artifactId>netty</artifactId>
     <version>3.1.0.GA</version>
  </dependency>
  <dependency>
     <groupId>org.jboss.javaee</groupId>
     <artifactId>jboss-jms-api</artifactId>
     <version>1.1.0.GA</version>
     <scope>compile</scope>
  </dependency>
    
  </dependencies>
</project>

Step 3) Place the basic hornetq configuration file in classpath.

hornetq-configuration.xml

<?xml version="1.0"?>
<configuration xsi:schemaLocation="urn:hornetq /schema/hornetq-configuration.xsd"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:hornetq">
	<connectors>
		<connector name="netty-connector">
			<factory-class>org.hornetq.integration.transports.netty.NettyConnectorFactory
			</factory-class>
		</connector>
	</connectors>
	<acceptors>
		<acceptor name="netty-acceptor">
			<factory-class>org.hornetq.integration.transports.netty.NettyAcceptorFactory
			</factory-class>
		</acceptor>
	</acceptors>
	<security-enabled>false</security-enabled>
</configuration>

Step 4) Configure the connector factory and place the configuration file in classpath.

hornetq-jms.xml

<?xml version="1.0"?>
<configuration xsi:schemaLocation="urn:hornetq /schema/hornetq-jms.xsd"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:hornetq">
	<!--the connection factory used by the example -->
	<connection-factory name="ConnectionFactory">
		<connectors>
			<connector-ref connector-name="netty-connector" />
		</connectors>
		<entries>
			<entry name="ConnectionFactory" />
		</entries>
	</connection-factory>
	<queue name="exampleQueue">
		<entry name="exampleQueue" />
	</queue>
</configuration>

Step 5) Start the server and test the messaging code

HornetQMessageQueueDemo.java

package com.howtodoinjava;

import java.util.HashMap;
import java.util.Map;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.hornetq.api.core.TransportConfiguration;
import org.hornetq.api.jms.HornetQJMSClient;
import org.hornetq.core.config.impl.FileConfiguration;
import org.hornetq.core.server.HornetQServer;
import org.hornetq.core.server.HornetQServers;
import org.hornetq.integration.transports.netty.NettyConnectorFactory;
import org.hornetq.integration.transports.netty.TransportConstants;
import org.hornetq.jms.server.JMSServerManager;
import org.hornetq.jms.server.impl.JMSServerManagerImpl;

public class HornetQMessageQueueDemo {
	
	static void startServer()
	{
		try
		  {
		     FileConfiguration configuration = new FileConfiguration();
		     configuration.setConfigurationUrl("hornetq-configuration.xml");
		     configuration.start();
		
		     HornetQServer server = HornetQServers.newHornetQServer(configuration);
		     JMSServerManager jmsServerManager = new JMSServerManagerImpl(server, "hornetq-jms.xml");
		     //if you want to use JNDI, simple inject a context here or don't call this method and make sure the JNDI parameters are set.
		     jmsServerManager.setContext(null);
		     jmsServerManager.start();
		     System.out.println("Server started !!");
		  }
		  catch (Throwable e)
		  {
		     System.out.println("Damn it !!");
		     e.printStackTrace();
		  }
	}
	
	public static void main(String[] args) throws Exception
	{
		//Start the server
		startServer();
		
		Connection connection = null;
		try 
		{
			// Step 1. Directly instantiate the JMS Queue object.
			Queue queue = HornetQJMSClient.createQueue("exampleQueue");

			// Step 2. Instantiate the TransportConfiguration object which
			// contains the knowledge of what transport to use,
			// The server port etc.

			Map<String, Object> connectionParams = new HashMap<String, Object>();
			connectionParams.put(TransportConstants.PORT_PROP_NAME, 5445);

			TransportConfiguration transportConfiguration = new TransportConfiguration(
																NettyConnectorFactory.class.getName(), connectionParams);

			// Step 3 Directly instantiate the JMS ConnectionFactory object
			// using that TransportConfiguration
			ConnectionFactory cf = HornetQJMSClient.createConnectionFactory(transportConfiguration);

			// Step 4.Create a JMS Connection
			connection = cf.createConnection();

			// Step 5. Create a JMS Session
			Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);

			// Step 6. Create a JMS Message Producer
			MessageProducer producer = session.createProducer(queue);

			// Step 7. Create a Text Message
			TextMessage message = session.createTextMessage("How to do in java dot com");

			System.out.println("Sent message: " + message.getText());

			// Step 8. Send the Message
			producer.send(message);

			// Step 9. Create a JMS Message Consumer
			MessageConsumer messageConsumer = session.createConsumer(queue);

			// Step 10. Start the Connection
			connection.start();

			// Step 11. Receive the message
			TextMessage messageReceived = (TextMessage) messageConsumer.receive(5000);

			System.out.println("Received message: " + messageReceived.getText());
		} 
		finally
		{
			if (connection != null) {
				connection.close();
			}
		}
	}
}


Output in console:

22 Mar, 2013 2:23:36 PM org.hornetq.core.logging.impl.JULLogDelegate info
INFO: live server is starting..
22 Mar, 2013 2:23:36 PM org.hornetq.core.logging.impl.JULLogDelegate warn
WARNING: AIO wasn't located on this platform, it will fall back to using pure Java NIO. If your platform is Linux, install LibAIO to enable the AIO journal
22 Mar, 2013 2:23:36 PM org.hornetq.core.logging.impl.JULLogDelegate info
INFO: Using NIO Journal
22 Mar, 2013 2:23:36 PM org.hornetq.core.logging.impl.JULLogDelegate warn
WARNING: Security risk! It has been detected that the cluster admin user and password have not been changed from the installation default. Please see the HornetQ user guide, cluster chapter, for instructions on how to do this.
22 Mar, 2013 2:23:36 PM org.hornetq.core.logging.impl.JULLogDelegate info
INFO: Started Netty Acceptor version 3.1.5.GA-r1772

Server started !!

22 Mar, 2013 2:23:36 PM org.hornetq.core.logging.impl.JULLogDelegate info
INFO: HornetQ Server version 2.0.0.GA (Hornet Queen, 113) started

Sent message: How to do in java dot com
Received message: How to do in java dot com

Download source code

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

11 thoughts on “HornetQ Stand Alone – Basic JMS Messaging Example”

  1. Hi ,Thanks for such a good demo with example.but i have to use topic instead of queue how will i configure and where can i configure it?

  2. Warning note to those who may discover this post: an important API used in this tutorial:

    ConnectionFactory cf = HornetQJMSClient.createConnectionFactory(transportConfiguration);

    does not even exist in later versions of HornetQ.

  3. Hi lokesh,

    I am new to hornetQ,i need to implement hornetQ in my SMS application which is presently using database Queue,can you please give me some suggestions how to start.

    thanks in advance

  4. HI Lokesh,

    Thanks for your tutorial. I would ike to know about integration of restful service developed in JAX-RS jersey. I am deploying it on JBoss AS 7.1. Now I have to use JMS in which MOM would be Hornetq Server to achieve asynchronous messaging. So, now I would like to know that how to integrate/call web service by url or by any means to get the result in json. My web service will return json string. How to achieve this. I am naive in JMS. However, i am going through the concept of JMS. I found the onMessage() method can be used. But I am not clear on this. Please provide me guidance and help with some sample piece of code.
    thanks
    Kumar Shorav

    • Above message appears only when hornetq-*.xml files are not present in classpath. Please copy them manually in they are not in classes folder.

      Apart from this, you will need to upgrade netty version also. In my system, current set of dependencies are :

      4.0.0
      com.howtodoinjava
      HornetQHelloWorld
      jar
      1.0-SNAPSHOT
      HornetQHelloWorld
      http://maven.apache.org

      junit
      junit
      3.8.1
      test

      org.hornetq
      hornetq-core
      2.2.5.Final
      compile

      org.hornetq
      hornetq-jms
      2.2.5.Final
      compile

      org.hornetq
      hornetq-logging
      2.2.5.Final
      compile

      org.hornetq
      hornetq-transports
      2.1.0.r9031
      compile

      org.jboss.netty
      netty
      3.2.3.Final

      org.jboss.javaee
      jboss-jms-api
      1.1.0.GA
      compile

      Also, remove all temp file in data folder. This can create problem. In my system, I am able to start the server with above changes but getting exception when sending the message:

      11 Apr, 2013 9:53:40 AM org.hornetq.core.logging.impl.JULLogDelegate warn
      WARNING: AIO wasn’t located on this platform, it will fall back to using pure Java NIO. If your platform is Linux, install LibAIO to enable the AIO journal
      11 Apr, 2013 9:53:40 AM org.hornetq.core.logging.impl.JULLogDelegate info
      INFO: live server is starting with configuration HornetQ Configuration (clustered=false,backup=false,sharedStore=true,journalDirectory=data/journal,bindingsDirectory=data/bindings,largeMessagesDirectory=data/largemessages,pagingDirectory=data/paging)
      11 Apr, 2013 9:53:40 AM org.hornetq.core.logging.impl.JULLogDelegate info
      INFO: Waiting to obtain live lock
      11 Apr, 2013 9:53:40 AM org.hornetq.core.logging.impl.JULLogDelegate info
      INFO: Using NIO Journal
      11 Apr, 2013 9:53:40 AM org.hornetq.core.logging.impl.JULLogDelegate warn
      WARNING: Security risk! It has been detected that the cluster admin user and password have not been changed from the installation default. Please see the HornetQ user guide, cluster chapter, for instructions on how to do this.
      11 Apr, 2013 9:53:40 AM org.hornetq.core.logging.impl.JULLogDelegate info
      INFO: Waiting to obtain live lock
      11 Apr, 2013 9:53:40 AM org.hornetq.core.logging.impl.JULLogDelegate info
      INFO: Live Server Obtained live lock
      11 Apr, 2013 9:53:41 AM org.hornetq.core.logging.impl.JULLogDelegate info
      INFO: trying to deploy queue jms.queue.exampleQueue
      11 Apr, 2013 9:53:41 AM org.hornetq.core.logging.impl.JULLogDelegate warn
      WARNING: Unexpected Netty Version was expecting 3.2.3.Final-r${buildNumber} using 3.2.0.BETA1-r2215
      11 Apr, 2013 9:53:41 AM org.hornetq.core.logging.impl.JULLogDelegate info
      INFO: Started Netty Acceptor version 3.2.0.BETA1-r2215 localhost:5445
      11 Apr, 2013 9:53:41 AM org.hornetq.core.logging.impl.JULLogDelegate info
      INFO: Server is now live
      11 Apr, 2013 9:53:41 AM org.hornetq.core.logging.impl.JULLogDelegate info
      INFO: HornetQ Server version 2.2.5.Final (HQ_2_2_5_FINAL_AS7, 121) [96933a41-a25f-11e2-91ec-002564ac1704] started
      Server started !!
      11 Apr, 2013 9:53:41 AM org.hornetq.core.logging.impl.JULLogDelegate warn
      WARNING: Unexpected Netty Version was expecting 3.2.3.Final-r${buildNumber} using 3.2.0.BETA1-r2215
      Sent message: How to do in java dot com
      11 Apr, 2013 9:53:41 AM org.hornetq.core.logging.impl.JULLogDelegate warn
      WARNING: Sending unexpected exception to the client
      java.lang.AbstractMethodError: org.hornetq.integration.transports.netty.NettyConnection.addReadyListener(Lorg/hornetq/spi/core/remoting/ReadyListener;)V
      at org.hornetq.core.protocol.core.impl.CoreSessionCallback.addReadyListener(CoreSessionCallback.java:97)
      at org.hornetq.core.server.impl.ServerConsumerImpl.(ServerConsumerImpl.java:171)
      at org.hornetq.core.server.impl.ServerSessionImpl.createConsumer(ServerSessionImpl.java:337)
      at org.hornetq.core.protocol.core.ServerSessionPacketHandler.handlePacket(ServerSessionPacketHandler.java:213)
      at org.hornetq.core.protocol.core.impl.ChannelImpl.handlePacket(ChannelImpl.java:474)
      at org.hornetq.core.protocol.core.impl.RemotingConnectionImpl.doBufferReceived(RemotingConnectionImpl.java:496)
      at org.hornetq.core.protocol.core.impl.RemotingConnectionImpl.bufferReceived(RemotingConnectionImpl.java:457)
      at org.hornetq.core.remoting.server.impl.RemotingServiceImpl$DelegatingBufferHandler.bufferReceived(RemotingServiceImpl.java:459)
      at org.hornetq.integration.transports.netty.HornetQChannelHandler.messageReceived(HornetQChannelHandler.java:67)
      at org.jboss.netty.channel.SimpleChannelHandler.handleUpstream(SimpleChannelHandler.java:100)
      at org.jboss.netty.channel.StaticChannelPipeline.sendUpstream(StaticChannelPipeline.java:362)
      at org.jboss.netty.channel.StaticChannelPipeline$StaticChannelHandlerContext.sendUpstream(StaticChannelPipeline.java:514)
      at org.jboss.netty.channel.Channels.fireMessageReceived(Channels.java:287)
      at org.hornetq.integration.transports.netty.HornetQFrameDecoder2.decode(HornetQFrameDecoder2.java:171)
      at org.hornetq.integration.transports.netty.HornetQFrameDecoder2.messageReceived(HornetQFrameDecoder2.java:136)
      at org.jboss.netty.channel.SimpleChannelUpstreamHandler.handleUpstream(SimpleChannelUpstreamHandler.java:80)
      at org.jboss.netty.channel.StaticChannelPipeline.sendUpstream(StaticChannelPipeline.java:362)
      at org.jboss.netty.channel.StaticChannelPipeline.sendUpstream(StaticChannelPipeline.java:357)
      at org.jboss.netty.channel.Channels.fireMessageReceived(Channels.java:274)
      at org.jboss.netty.channel.Channels.fireMessageReceived(Channels.java:261)
      at org.jboss.netty.channel.socket.oio.OioWorker.run(OioWorker.java:90)
      at org.jboss.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108)
      at org.jboss.netty.util.internal.IoWorkerRunnable.run(IoWorkerRunnable.java:46)
      at org.jboss.netty.util.VirtualExecutorService$ChildExecutorRunnable.run(VirtualExecutorService.java:181)
      at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
      at java.lang.Thread.run(Unknown Source)
      Exception in thread “main” javax.jms.JMSException
      at org.hornetq.core.protocol.core.impl.ChannelImpl.sendBlocking(ChannelImpl.java:286)
      at org.hornetq.core.client.impl.ClientSessionImpl.internalCreateConsumer(ClientSessionImpl.java:1685)
      at org.hornetq.core.client.impl.ClientSessionImpl.createConsumer(ClientSessionImpl.java:461)
      at org.hornetq.core.client.impl.ClientSessionImpl.createConsumer(ClientSessionImpl.java:427)
      at org.hornetq.core.client.impl.DelegatingSession.createConsumer(DelegatingSession.java:188)
      at org.hornetq.jms.client.HornetQSession.createConsumer(HornetQSession.java:537)
      at org.hornetq.jms.client.HornetQSession.createConsumer(HornetQSession.java:383)
      at org.hornetq.jms.client.HornetQSession.createConsumer(HornetQSession.java:353)
      at com.howtodoinjava.HornetQMessageQueueDemo.main(HornetQMessageQueueDemo.java:92)
      Caused by: HornetQException[errorCode=0 message=null]
      … 9 more

      Anyway, I will work on this when find time.. and update here.

  5. Tried to follow this nice tutorial however I keep getting this error:
    “java.net.MalformedURLException: no protocol: hornetq-configuration.xml
    at java.net.URL.(URL.java:585)
    at java.net.URL.(URL.java:482)
    at java.net.URL.(URL.java:431)
    at org.hornetq.core.config.impl.FileConfiguration.start(FileConfiguration.java:67)
    at com.howtodoinjava.HornetQMessageQueueDemo.startServer(HornetQMessageQueueDemo.java:28)
    at com.howtodoinjava.HornetQMessageQueueDemo.main(HornetQMessageQueueDemo.java:40)”

    when trying to start the server .
    using hornerq 2.2.5.Final so this line changed: ConnectionFactory cf = (ConnectionFactory)HornetQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF,transportConfiguration);

    any idea how to fix it

Comments are closed.

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.