Thursday, March 15, 2012

HornetQ inside OSGi Container

Recently I got chance to experiment with HornetQ message broker and idea was to run the broker as a service within OSGI container. The flexibility it offers is what impressed me along with the well proven performance.
In the process, I learnt it is possible to embed this MQ broker into any application, and that way one could completely avoid an external server to hold the broker logic. This could for sure make IT management happy where in they don't have to manage extra server just for running broker service. The implementation was a cake walk but with OSGI container in place, it called for some in depth understanding of the HornetQ architecture, as HorentQ libraries are not OSGI complaint.

To save someone's time, I thought of sharing this information on how to setup/embed HornetQ broker in an application with OSGI container.
Prerequisites : Maven, Tomcat, Apache Felix, SLF4J.
Step 1 : Download below HornetQ jars (I have used 2.0.0.GA version here).
hornetq-core.jar
hornetq-jms.jar
hornetq-logging.jar
hornetq-transports.jar
netty.3.1.0.jar
jboss-jms-api.jar

Step 2 : The above jars are not OSGI complaint (except netty.jar) and it is required to first convert them as OSGI bundles. I have used bnd tool to bundle these jars and one important note is to set the version of the bundles as 0.0.0 as it fails the auto wiring without that.

Step 3 :
After creating the bundles, we need to create a java maven project with all the above dependent bundles. Either add below configuration xmls in src\main\resoruces folder or write logic to include those configurable parameters.

hornetq-configuration.xml
hornetq-jms.xml
Step 4 :
Create Activator class and in start method write logic (give below) to start the broker service. This way as soon as bundle is started in side OSGI container, the broker starts and listens to messages in the configured port.

public void startServer(BundleContext context) {

try {

FileConfiguration configuration = new FileConfiguration();
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
String configURL = context.getBundle().getEntry("hornetq-configuration.xml").getPath();
String configRes = context.getBundle().getResource("hornetq-configuration.xml").getPath();
configuration.setConfigurationUrl(configURL);
configuration.start();
HornetQServer server = HornetQServers.newHornetQServer(configuration);
JMSServerManager jmsServerManager = new JMSServerManagerImpl(server, "hornetq-jms.xml");
jmsServerManager.setContext(null);
jmsServerManager.start();
logger.info("HORNETQ SERVER STARTED::");
}
catch (Exception e) {
logger.error(" Error starting server ",e);
}
}

Step 5:
Run maven command to compile and create bundle.

Step 6:
deploy the bundle in the OSGI container and start the bundle.

The broker should be running and now write a client to test this setup.

No comments:

Post a Comment