Tuesday, October 14, 2014

Quick Tutorial on ActiveMQ Web Console In 5 minutes

There are some basic operations when developing with ActiveMQ:

All these operations can be done by using a web browser, because ActiveMQ broker provides a web console default on port 8161. For example if you run your ActiveMQ broker:

# ACTIVEMQ_INSTALL_DIR is the path where you install ActiveMQ
ACTIVEMQ_INSTALL_DIR/bin/activemq start

Then you can access the web console  from url http://localhost:8161/admin. Replace the 'localhost' to the server's IP if you try to access the ActiveMQ web console remotely.


image


Browse all Queues (Queues List)


Click the Queues menu or access Http://localhost:8161/admin/queues.jsp , all queues will list out.


image


The highlight "3" means there are 3 messages in the broker waiting to be received.


Browse  all messages in a Queue (Message List)


From Queues List page, You can click a queue's name to browser all messages pending in that queue.


image


Check detailed information of any message


Click on the message Id, then you can see the details of the message. A message is composed by message header and message body.  image



Create a Message manually from web


If the destination queue exists, then from the queue list page, click the Send To link. If the destination queue does not exists, you can click Send from the menu, and give a name of the destination, the queue will be create automatically when sending message.


image


Type the text content, then click send .


image


Delete a specified message in a Queue


From the message list of the Queue, click Delete to remove message.


image


Delete all messages of a Queue


From the Queue list, click Purge.


image

Spring JMS with ActiveMQ - hello world example - receive message using message listener adapter

This tutorial will demo how to receive message by using Spring JMS and ActiveMQ. This tutorial uses Spring JMS's MessageListenerAdapter. Compare to receiving message using MessageListener interface, there are 2 advantages you can get:

  1. Use any POJO class as real message listener, no need to implements any interface in your Java class.
  2. Easy to send message back in most cases.

There are other ways to  receive message from ActiveMQ broker using Spring JMS, examples are provided here

The example on how to send out message with Spring JMS and ActiveMQ is in this article.

1. What you need

  • JDK 1.7+
  • Maven 3.2.1
  • ActiveMQ 5.10.0
  • Spring 4.1.0.RELEASE  (acquired by Maven)
We’ll use maven to manage all dependencies.  To write code there is no need for ActiveMQ binary, since maven will take care of the ActiveMQ library we need. But to run the code, we need the ActiveMQ binary, In this example  we'll run the ActiveMQ broker on a machine of IP 192.168.203.143 with default port 61616. If you run the broker in a different IP or port, don't forget to change the broker URL in Spring configuration file.

2. Configure the maven  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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.samples</groupId>
<artifactId>spring-jms-activemq-receive-direct</artifactId>
<version>0.0.1-SNAPSHOT</version>

<properties>

<!-- Spring Version -->
<spring-framework.version>4.1.0.RELEASE</spring-framework.version>

<!-- ActiveMQ Version -->
<activemq.version>5.10.0</activemq.version>

</properties>

<dependencies>
<!-- Spring Artifacts-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>${spring-framework.version}</version>
</dependency>

<!-- ActiveMQ Artifacts -->
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
<version>${activemq.version}</version>
</dependency>

</dependencies>

<!-- Use JDK 1.7+ -->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

As you can see from the maven pom.xml file, we use 3 key artifacts in this example, spring-context, spring-jms and activemq-all.  The first 2 belong to spring framework and the last one is ActiveMQ  implementation for jms.  The final part of the pom file specified the JDK version for compiling.



3. Define the Java Class


We are going to define 2 classes. The first one is a simple spring bean:
package com.shengwang.demo;

import org.springframework.stereotype.Service;

@Service
/**
* POJO class, have handleMessage(...) method.
* The return of handleMessage(...) will be
* automatically send back to message.getJMSReplyTo().
*/
public class JmsMessageListener {

public String handleMessage(String text) {
System.out.println("Received: " + text);
return "ACK from handleMessage";
}
}

The above JmsMessageListener Class is just a POJO java class, which has neither parent class nor interface implementation. The JmsMessageListener annotated by @Service as spring bean. The default listener method that will be invoked is "handleMessage" for MessageListenerAdapter, but can be changed to different method  in Spring Configuration.

Anything return from handleMessage will be send out as a message back to JMS broker. The destination will be the ReplyTo header of the incoming message. If it's not set, reply message will be send to default destination.

One thing need to mention is something called MessageConvertor. MesssageConvertor will be called before and after the method handleMessage. MessageConvertor is set in Spring configuration for MessageListenerAdapter bean. If not specified, a default one from spring will be used. The default Spring  MessageConvertor converts received message to normal Java data types as input parameter of  handleMessage before invoking.  After handleMessage finishes, it converts return to a kind of  JMS message.

In this demo, a received ActiveMQTextMessage  object is transferred to a String object before calling handleMessage. A return String object is transferred back to a TextMessage object.

How or where is this JmsMessageListener  class registered for receiving message? It's all in the spring configuration file. we'll come to this in the below. Now let’s take a glance at the main class.

package com.shengwang.demo;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class DemoMain {

public static void main(String[] args) {
// create Spring context
ApplicationContext ctx = new ClassPathXmlApplicationContext("app-context.xml");

// sleep for 1 second
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

// close application context
((ClassPathXmlApplicationContext)ctx).close();
}
}
In the main, one thing to notice is there is no trace of the message listener we just defined. Because the message listener will be call asynchronously , you do (can)  not to invoke it explicitly.

Also we use ClassPathXmlApplicationContext to lookup all spring beans in spring configuration file called “app-context.xml”.  We wait for 1 second to let our message listener do it's job, then at the end of main, we close the spring context.



4. spring configuration


Our spring configuration file is named “app-context.xml”. It stays in the man resource path /src/main/resources/ to store the spring configuration file. In the configuration file, we define beans in this order:

Connection Factory  bean (ActiveMQ) –> cached Connection Factory  bean ( Spring jms) –> MessageListenerAdapter bean(Spring jms) ->MessageListenerContainer bean(Spring jms).

The cached connection factory bean is necessary because the Spring will open/close connection on every send or receive action.  So in practical there will always a cached connection factory bean beside the direct connection factory bean.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">


<context:component-scan base-package="com.shengwang.demo" />


<!-- =============================================== -->
<!-- JMS Common, Define Jms connection factory -->
<!-- =============================================== -->
<!-- Activemq connection factory -->
<bean id="amqConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<!-- brokerURL -->
<constructor-arg index="0" value="tcp://192.168.203.143:61616" />
</bean>

<!-- Pooled Spring connection factory -->
<bean id="connectionFactory"
class="org.springframework.jms.connection.CachingConnectionFactory">
<constructor-arg ref="amqConnectionFactory" />
</bean>



<!-- ============================================================= -->
<!-- JMS receive. -->
<!-- Define MessageListenerAdapter and MessageListenerContainer -->
<!-- ============================================================= -->
<bean id="messageListenerAdapter"
class="org.springframework.jms.listener.adapter.MessageListenerAdapter">
<constructor-arg ref="jmsMessageListener" />
</bean>

<bean id="messageListenerContainer"
class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory" />
<property name="destinationName" value="Send2Recv" />
<property name="messageListener" ref="messageListenerAdapter" />
</bean>

</beans>

As you can see from the Spring configuration file, <context:component-scan ...> is used to let spring find out all beans automatically. In our example we have defined only one bean, jmsMessageListener . Next we define connection factories. The ActiveMQ's connection factory bean works as an input of Spring's pooled connection factory. These 2 connection factory beans will be needed both for sending and receiving messages. 

Next we wrap the POJO class JmsMessageListener by Spring MessageListenerAdapter. Our jmsMessageListener bean is constructor parameter of messageListenerAdapter bean.

Finally we define MessageListenerContainer bean. Spring use MessageListenerContainer to manager messageListener beans. After connection factory beans, we define a bean of spring's DefaultMessageListenerContainer . There are 3 parameters set for this bean. connectionFactory is for connection, destinationName is the Queue's name to receive message from.  messageListener refer to our messageListenerAdapter bean which we wrapped our JmsMessageListener  POJO class with Spring MessageMessageListenerAdapter. So it's here we let spring context know where to receive  messages, and what  to do when a message arrives.

Everything is almost done now. Let's review the directory structure for our maven project.
image



5. Run the code


Before you can run the code, you need to make sure the ActiveMQ broker is running. So our jave code can connect to it and receive message from it.   Make sure the broker IP and port are correct in your spring configuration file "app-context.xml". Run the ActiveMQ broker like with this command.
ACTIVEMQ_INSTALL_DIR/bin/activemq start

Now you can run you main class.  you can run it from IDE such as eclipse, or you can run it direct in command line by using maven.
cd spring-jms-activemq-send
# run mvn from project directory
mvn exec:java -Dexec.mainClass="com.shengwang.demo.DemoMain"

ActiveMQ broker can be managed by browser on port 8161.  My ActiveMQ broker is running on IP 192.168.203.143, so I can access URL http://192.168.203.143:8161/admin to browse all queues and all messages in the queues. If there is no message in the broker, the main will sleep 1 second, do nothing and exit.  To better show how the message listener works, you can either run the sender example in this example, which will send a message to destination "Send2Recv", or create a message manually from ActiveMQ Web Console by using browser (Don't forget to set "ReplyTo" in the created message's header, cause we need it to send reply back in this example).

For demo, I send 2 messages with different ReplyTo in its message header.

image 
Then we run the message listener main. After running the main of this message listener example, the pending messages in Queue "Send2Recv" are gone. Two messages are replied to different destinations.

image


The content of the message is the return String of listener method handleMessage in class JmsMessageListener.

image

Friday, October 10, 2014

Spring JMS with ActiveMQ - hello world example - receive message using direct message listener

This tutorial will demo how to receive message by using Spring JMS and ActiveMQ. This tutorial uses class directly implements Spring JMS's MessageListener or SessionAwareMessageListener interface. There are other ways to  receive message from ActiveMQ broker using Spring JMS, examples are provided here.

The example on how to send out message with Spring JMS and ActiveMQ is in this article

1. What you need

  • JDK 1.7+
  • Maven 3.2.1
  • ActiveMQ 5.10.0
  • Spring 4.1.0.RELEASE  (acquired by Maven)
We’ll use maven to manage all dependencies.  To write code there is no need for ActiveMQ binary, since maven will take care of the ActiveMQ library we need. But to run the code, we need the ActiveMQ binary, In this example  we'll run the ActiveMQ broker on a machine of IP 192.168.203.143 with default port 61616. If you run the broker in a different IP or port, don't forget to change the broker URL in Spring configuration file.

2. Configure the maven  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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.samples</groupId>
<artifactId>spring-jms-activemq-receive-direct</artifactId>
<version>0.0.1-SNAPSHOT</version>

<properties>

<!-- Spring -->
<spring-framework.version>4.1.0.RELEASE</spring-framework.version>

<!-- ActiveMQ -->
<activemq.version>5.10.0</activemq.version>

</properties>

<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>${spring-framework.version}</version>
</dependency>

<!-- ActiveMQ Artifacts -->
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
<version>${activemq.version}</version>
</dependency>

</dependencies>

<!-- Use JDK 1.7+ -->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>


As you can see from the maven pom.xml file, we use 3 key artifacts in this example, spring-context, spring-jms and activemq-all.  The first 2 belong to spring framework and the last one is ActiveMQ  implementation for jms.  The final part of the pom file specified the JDK version for compiling.



3. Define the Java Class


We are going to define 2 classes. The first one is a simple spring bean:
package com.shengwang.demo;

import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.command.ActiveMQTextMessage;
import org.springframework.jms.listener.SessionAwareMessageListener;
import org.springframework.stereotype.Service;

@Service
/**
* Listener Implement Spring SessionAwareMessageListener Interface
*
*/
public class JmsMessageListener implements SessionAwareMessageListener {

@Override
public void onMessage(TextMessage message, Session session) throws JMSException {
// This is the received message
System.out.println("Receive: "+message.getText());

// Let's prepare a reply message - a "ACK" String
ActiveMQTextMessage textMessage = new ActiveMQTextMessage();
textMessage.setText("ACK");

// Message send back to the replyTo address of the income message.
// Like replying an email somehow.
MessageProducer producer = session.createProducer(message.getJMSReplyTo());
producer.send(textMessage);
}
}



In the above JmsMessageListener Class, it implements Spring's SessionAwareMessageListener interface and the method defined in the interface, the onMessage method. This onMessage method will be called asynchronously on every message arriving. Look through the code, we add @service annotation to make JmsMessageListener class a Spring bean. The onMessage takes 2 parameters.  First one is the message, second one is the Session which you can use to send  out a reply message.


You may be aware of that the JmsMessageListener class implements the interface SessionAwareMessageListener instead of interface MessageListener. The only difference is SessionAwareMessageListener will give one more parameter for method onMessage, Session, which can be used to send message back in you listener.


In the onMessage method, we deal with the income message, print out the content to screen, then create a text message and finally send it back. We use the replyTo info of the income message as the destination to send out.  This somehow really seems like the mechanism of replying a email.  If there is no replyTo info set in the message header of the income message, you need to explicit define a destination to reply.



How or where is this JmsMessageListener  class registered for receiving message? It's all in the spring configuration file. we'll come to this in the below. Now let’s take a glance at the main class.

package com.shengwang.demo;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class DemoMain {

public static void main(String[] args) {
// create Spring context
ApplicationContext ctx = new ClassPathXmlApplicationContext("app-context.xml");

// sleep for 1 second
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

// close application context
((ClassPathXmlApplicationContext)ctx).close();
}
}

In the main, one thing to notice is there is no trace of the message listener we just defined. Because the message listener will be call asynchronously , you do (can)  not to invoke it explicitly.
Also we use ClassPathXmlApplicationContext to lookup all spring beans in spring configuration file called “app-context.xml”.  We wait for 1 second to let our message listener do it's job, then at the end of main, we close the spring context.



4. spring configuration


Our spring configuration file is named “app-context.xml”. It stays in the man resource path /src/main/resources/ to store the spring configuration file. In the configuration file, we define beans in this order:

Connection Factory  bean (by jms provider ActiveMQ) –> cached Connection Factory  bean ( by Spring jms) –> MessageListenerContainer bean (by spring jms).

The cached connection factory bean is necessary because the Spring will open/close connection on every send or receive action.  So in practical there will always a cached connection factory bean beside the direct connection factory bean.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">


<context:component-scan base-package="com.shengwang.demo" />

<!-- =============================================== -->
<!-- JMS Common,Define JMS connection Factory -->
<!-- =============================================== -->
<!-- Activemq connection factory -->
<bean id="amqConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<!-- brokerURL -->
<constructor-arg index="0" value="tcp://192.168.203.143:61616" />
</bean>

<!-- Pooled Spring connection factory -->
<bean id="connectionFactory"
class="org.springframework.jms.connection.CachingConnectionFactory">
<constructor-arg ref="amqConnectionFactory" />
</bean>



<!-- ============================================================= -->
<!-- JMS Receive,Define MessageListenerContainer -->
<!-- ============================================================= -->
<bean id = "messageListenerContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory"/>
<property name="destinationName" value="Send2Recv"/>
<property name="messageListener" ref="jmsMessageListener"/>
</bean>

</beans>



As you can see from the Spring configuration file, we use <context:component-scan ...> to let spring find out all beans automatically. In our example we have defined only one bean, jmsMessageListener . Next we define connection factories. The ActiveMQ's connection factory bean works as an input of Spring's pooled connection factory. These 2 connection factory beans will be needed both for sending and receiving messages. 



Spring use MessageListenerContainer to manager messageListener beans. After connection factory beans, we define a bean of spring's DefaultMessageListenerContainer . There are 3 parameters set for this bean. connectionFactory is for connection, destinationName is the Queue's name to receive message from.  messageListener refer to our jmsMessageListener bean which we defined in the Java class JmsMessageListener above. So it's here we let spring context know where to receive  messages, and what  to do when a message arrives.

Everything is almost done now. Let's review the directory structure for our maven project.
image



5. Run the code


Before you can run the code, you need to make sure the ActiveMQ broker is running. So our jave code can connect to it and receive message from it.   Make sure the broker IP and port are correct in your spring configuration file "app-context.xml". Run the ActiveMQ broker like with this command.
ACTIVEMQ_INSTALL_DIR/bin/activemq start

Now you can run you main class.  you can run it from IDE such as eclipse, or you can run it direct in command line by using maven.
cd spring-jms-activemq-send
# run mvn from project directory
mvn exec:java -Dexec.mainClass="com.shengwang.demo.DemoMain"


ActiveMQ broker can be managed by browser on port 8161.  My ActiveMQ broker is running on IP 192.168.203.143, so I can access URL http://192.168.203.143:8161/admin to browse all queues and all messages in the queues. If there is no message in the broker, the main will sleep 1 second, do nothing and exit.  To better show how the message listener works, you can either run the sender example in this example, which will send a message to destination "Send2Recv", or create a message manually from ActiveMQ Web Console by using browser (Don't forget to set "ReplyTo" in the created message's header, cause we need it to send reply back in this example).


image 
Then we run the message listener main. After running the main of this message listener example, the messages in Queue "Send2Recv" are gone. There are 2 new message on the Queue "Recv2Send", they are our ack reply message which we send back in the onMessage method of the listener.





image

Tuesday, October 7, 2014

Spring JMS with ActiveMQ – hello world example – send message

Before we start, let make some concepts clear .  What’s the role for each part of the JMS/Spring JMS/ActiveMQ combination.
What’s JMS ? In short, JMS is a set of APIs defined in JSR. In practical you can think it’s a set of Java Interfaces. JMS is part of the JEE standard coming with JDK in package javax.jms.*  There are basically 2 versions of JMS, JMS 1.x and JMS 2.0. These 2 sets of APIs are different.
What’s ActiveMQ? In short ActiveMQ is one of the implementation of JMS APIs (Of course there are other implementations, Open JMS, RabbitMQ for example).  ActiveMQ also provide the broker which can be treated somehow  like a server, that you can send message to or receive message from. For now, 2014-10, ActiveMQ only implements the interfaces defined in  JMS 1.1 version. 
What’s Spring JMS? Spring JMS is part of  the whole spring framework. It wrap the real JMS service provider such as ActiveMQ or OpenJMS, provides consistent APIs to upper logic. Spring  JMS’s APIs are quite similar to JMS2.0  in JEE7. Spring JMS can decouple you business logic from the real JMS service provider, which here in our example is apache ActiveMQ.
In this example we are going to create a example to send out a text message by using Spring JMS and ActiveMQ. 

1. What you need

  • JDK 1.7
  • Maven 3.2.1
  • ActiveMQ 5.10.0
  • Spring 4.1.0.RELEASE  (acquired by Maven)
We’ll use maven to manage all dependencies.  To write code there is no need for ActiveMQ binary, since maven will take care of the ActiveMQ library we need. But to run the code, we need the ActiveMQ binary, In this example  we'll run the ActiveMQ broker on a machine of IP 192.168.203.143 with default port 61616. If you run the broker in a different IP or port, don't forget to change the broker URL in Spring configuration file.

2. Configure the maven  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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.samples</groupId>
<artifactId>spring-jms-activemq-send</artifactId>
<version>0.0.1-SNAPSHOT</version>

<properties>
<!-- Spring version -->
<spring-framework.version>4.1.0.RELEASE</spring-framework.version>
<!-- ActiveMQ version -->
<activemq.version>5.10.0</activemq.version>
</properties>

<dependencies>
<!-- Spring aritifacts -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>${spring-framework.version}</version>
</dependency>

<!-- ActiveMQ Artifacts -->
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-spring</artifactId>
<version>${activemq.version}</version>
</dependency>
</dependencies>

<!-- Using JDK 1.7 for compiling -->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

As you can see from the maven pom.xml file, we use 3 key artifacts in this example, spring-context, spring-jms and activemq-spring.  The first 2 belong to spring framework and the last one is ActiveMQ  implementation for jms.  The final part of the pom file specified the JDK version for compiling.



3. Define the Java Class


We are going to define 2 classes. The first one is a simple spring bean:
package com.shengwang.demo;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

@Service
public class JmsMessageSender {

@Autowired
private JmsTemplate jmsTemplate;


/**
* send text to default destination
* @param text
*/
public void send(final String text) {

this.jmsTemplate.send(new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
Message message = session.createTextMessage(text);
//set ReplyTo header of Message, pretty much like the concept of email.
message.setJMSReplyTo(new ActiveMQQueue("Recv2Send"));
return message;
}
});
}

/**
* Simplify the send by using convertAndSend
* @param text
*/
public void sendText(final String text) {
this.jmsTemplate.convertAndSend(text);
}

/**
* Send text message to a specified destination
* @param text
*/
public void send(final Destination dest,final String text) {

this.jmsTemplate.send(dest,new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
Message message = session.createTextMessage(text);
return message;
}
});
}
}

In the above JmsMessageSender Class, Spring's JmsTemplate is used to do the send message task. You can find out how this bean is defined in spring configuration file below.  There are 1 sendText method and 2 send methods in the class. The 2 send methods both take String parameter text as message payload to be sent. The different is the later send take one more Destination parameter to specify where to send the message. the first one will simply send the message to the default destination.  The sendText method simplify the send by using Spring JmsTemplate’s convertAndSend method which will automatically create the TextMessage object from the input String object and send it.  convertAndSend  can save you from creating the TextMessage object yourself.

Next let’s see how to use the above JmsMessageSender class in the main class.
package com.shengwang.demo;

import javax.jms.Queue;

import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class DemoMain {

public static void main(String[] args) {
// init spring context
ApplicationContext ctx = new ClassPathXmlApplicationContext("app-context.xml");

// get bean from context
JmsMessageSender jmsMessageSender = (JmsMessageSender)ctx.getBean("jmsMessageSender");

// send to default destination
jmsMessageSender.send("hello JMS");

// send to a code specified destination
Queue queue = new ActiveMQQueue("AnotherDest");
jmsMessageSender.send(queue, "hello Another Message");

// close spring application context
((ClassPathXmlApplicationContext)ctx).close();
}

}

In the main, we send out 2 text message by using the JmsMessageSender bean we have defined.  One thing to notice is how to send out the second message. We create a ActiveMQQueue as destination. and send the second message to this queue. We use ActiveMQ as our JMS service provider. If we use another JMS service provider like OpenJMS, we may need to change ActiveMQQueue  to OpenJMS provided Queue implementation.

Also we use ClassPathXmlApplicationContext to lookup all spring beans in spring configuration file called “app-context.xml”.  At main end, we close the spring context.



4. spring configuration


Our spring configuration file is named “app-context.xml”. It stays in the man resource path /src/main/resources/ to store the spring configuration file. In the configuration file, we define beans in this order:

Connection Factory  bean (by jms provider ActiveMQ) –> cached Connection Factory  bean ( by Spring jms) –> JmsTemplate bean (by spring).

The cached connection factory bean is necessary because the Spring JmsTemplate will open/close connection on every send or receive action.  So in practical there will always a cached connection factory bean beside the direct connection factory bean.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">


<context:component-scan base-package="com.shengwang.demo" />


<!-- =============================================== -->
<!-- JMS Common, Define JMS connectionFactory -->
<!-- =============================================== -->
<!-- Activemq connection factory -->
<bean id="amqConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<!-- brokerURL, You may have different IP or port -->
<constructor-arg index="0" value="tcp://192.168.203.143:61616" />
</bean>

<!-- Pooled Spring connection factory -->
<bean id="connectionFactory"
class="org.springframework.jms.connection.CachingConnectionFactory">
<constructor-arg ref="amqConnectionFactory" />
</bean>

<!-- ======================================================= -->
<!-- JMS Send, define default destination and JmsTemplate -->
<!-- ======================================================= -->
<!-- Default Destination Queue Definition -->
<bean id="defaultDestination" class="org.apache.activemq.command.ActiveMQQueue">
<!-- name of the queue -->
<constructor-arg index="0" value="Send2Recv" />
</bean>

<!-- JmsTemplate Definition -->
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="connectionFactory" />
<property name="defaultDestination" ref="defaultDestination" />
</bean>

</beans>


As you can see from the Spring configuration file, we use <context:component-scan ...> to let spring find out all beans automatically. In our example we have defined only one bean, jmsMessageSender . Next we define connection factories. The ActiveMQ's connection factory bean works as an input of Spring's pooled connection factory. These 2 connection factory beans will be needed both for sending and receiving messages.  After connection factory beans, we define a destination used as default destination. It's a  queue with name "Send2Recv". Finally there's the Spring JmsTemplate bean. It use the connection factory and defaultDestination bean we create above. If you don't define default destination for JmsTemplate, you will need to explicitly set destination when you try to send any message in your java code.

The Jms service provider's bean, namely ActiveMQ related beans,  will NOT be used in your code directly. There are the input of Spring JMS.  You code use beans from Spring JMS instead.

Everything is almost done now. Let's review the directory structure for our maven project.

image



5. Run the code


Before you can run the code, you need to make sure the ActiveMQ broker is running. So our jave code can connect to it and send message to it.   Make sure the broker IP and port are correct in your spring configuration file "app-context.xml". Run the ActiveMQ broker like with this command.
ACTIVEMQ_INSTALL_DIR/bin/activemq start

Now you can run you main class.  you can run it from IDE such as eclipse, or you can run it direct in command line by using maven.
# run this from project directory
cd spring-jms-activemq-send
mvn exec:java -Dexec.mainClass="com.shengwang.demo.DemoMain"

It should run quietly without any error. After running your main, you can check the result through ActiveMQ's administration tool. ActiveMQ can be managed by browser on port 8161.  My ActiveMQ broker is running on IP 192.168.203.143, so I can access URL http://192.168.203.143:8161/admin to browse all queues and all messages in the queues.

image As you can see after running the main, there are 2 queues created on the broker. One is named "Send2Recv" which we used as default destination, the other one is "AnotherDest" which we create in the main class. By click into the queue, all message be list out, click any message can see the detain of that message , including message header and message content.

image image

6. More


Here are more hello world level examples on how to receive message from JMS with Spring jms and ActiveMQ.

Powered by Blogger.

About The Author

My Photo

Has been a senior software developer, project manager for 10+ years. Dedicate himself to Alcatel-Lucent and China Telecom for delivering software solutions.

Pages

Unordered List