Spring JMS ActiveMQ Topic Example

来源:互联网 发布:国家护理数据 编辑:程序博客网 时间:2024/04/29 16:34

Application(s) Overview:

In our post, we have 3 applications A & B & C trying to communicate with each other via sending Messages on Topic. 

A sends a message [a pojo object] to a Topic [order-topic]. B and C are listening on order-topic. A short but simple example of inter-application communication using JMS. Let’s start with coding Application A. Application B and C are exactly same as A.

springJMSproducerTopic code as following:

Step 1. Messaging Configuration using Spring & ActiveMQ

<?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"        xmlns:mongo="http://www.springframework.org/schema/data/mongo"      xmlns:aop="http://www.springframework.org/schema/aop"    xsi:schemaLocation="http://www.springframework.org/schema/beans               http://www.springframework.org/schema/beans/spring-beans-3.0.xsd              http://www.springframework.org/schema/data/mongo              http://www.springframework.org/schema/data/mongo/spring-mongo.xsd            http://www.springframework.org/schema/context       http://www.springframework.org/schema/context/spring-context-3.0.xsd     http://www.springframework.org/schema/aop        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">  <context:component-scan base-package="com.npf"/><bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory"><property name="brokerURL" value="tcp://localhost:61616"/></bean><bean id="topic" class="org.apache.activemq.command.ActiveMQTopic"><property name="physicalName" value="order-topic"/></bean><bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate"><property name="connectionFactory" ref="connectionFactory"/><property name="pubSubDomain" value="true"/></bean></beans>
JmsTemplate is all you need to send the messages. It comes with several methods[send*,convertAndSend*] to choose from while sending the messages.

package com.npf.service.impl;import javax.jms.Destination;import javax.jms.JMSException;import javax.jms.Message;import javax.jms.ObjectMessage;import javax.jms.Session;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.jms.core.JmsTemplate;import org.springframework.jms.core.MessageCreator;import org.springframework.stereotype.Service;import com.npf.model.Product;import com.npf.service.ProductService;import com.npf.util.JsonUtil;@Service("productService")public class ProductServiceImpl implements ProductService{static final Logger LOG = LoggerFactory.getLogger(ProductServiceImpl.class);@Autowiredprivate JmsTemplate jmsTemplate;@Autowired@Qualifier("topic")private Destination topic;@Overridepublic void sendProduct(Product product) {final String json = JsonUtil.converBeanToJson(product);LOG.info("PRODUCER sending request {}", json); jmsTemplate.send(topic,new MessageCreator(){             @Override             public Message createMessage(Session session) throws JMSException{                 ObjectMessage objectMessage = session.createObjectMessage(json);                 return objectMessage;             }         });}}
That’s all for Application A setup. Below shown is the Directory Structure for Project A.


Before we start both the applications and see message transfer in action, shown below is the directory structure and configuration code for Application B and C[Mirror image].




springJMSconsumerTopic1 code as following:

<?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"        xmlns:mongo="http://www.springframework.org/schema/data/mongo"      xmlns:aop="http://www.springframework.org/schema/aop"    xsi:schemaLocation="http://www.springframework.org/schema/beans               http://www.springframework.org/schema/beans/spring-beans-3.0.xsd              http://www.springframework.org/schema/data/mongo              http://www.springframework.org/schema/data/mongo/spring-mongo.xsd            http://www.springframework.org/schema/context       http://www.springframework.org/schema/context/spring-context-3.0.xsd     http://www.springframework.org/schema/aop        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">  <context:component-scan base-package="com.npf"/><bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory"><property name="brokerURL" value="tcp://localhost:61616"/></bean><bean id="topic" class="org.apache.activemq.command.ActiveMQTopic"><property name="physicalName" value="order-topic"/></bean><bean id="messageListenerContainer " class="org.springframework.jms.listener.DefaultMessageListenerContainer"><property name="connectionFactory" ref="connectionFactory"/><property name="destination"   ref="topic"/><property name="messageListener" ref="messageReceiver"/><property name="pubSubDomain" value="true"/></bean><bean id="messageConverter" class="org.springframework.jms.support.converter.SimpleMessageConverter"/></beans>


package com.npf.receiver;import javax.jms.JMSException;import javax.jms.Message;import javax.jms.MessageListener;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.jms.support.converter.MessageConverter;import org.springframework.stereotype.Component;import com.fasterxml.jackson.core.type.TypeReference;import com.npf.model.Product;import com.npf.util.JsonUtil;@Componentpublic class MessageReceiver implements MessageListener{     static final Logger LOG = LoggerFactory.getLogger(MessageReceiver.class);         @Autowired    private MessageConverter messageConverter;          @SuppressWarnings("unused")@Override    public void onMessage(Message message) {        try {            String json = (String) messageConverter.fromMessage(message);            LOG.info("CONSUMER 1 : received : {}",json);              Product product = JsonUtil.convertJsonToBean(json, new TypeReference<Product>(){});        } catch (JMSException e) {                    }             }}
springJMSconsumerTopic2 code is same as springJMSconsumerTopic1.

That is all.

springJMSproducerTopic ProducerApplication.java

package com.npf.test;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.npf.model.Product;import com.npf.service.ProductService; public class ProducerApplication {     static final Logger LOG = LoggerFactory.getLogger(ProducerApplication.class);         @SuppressWarnings("resource")public static void main(String[] args){        ApplicationContext context = new ClassPathXmlApplicationContext("spring/applicationContext.xml");        ProductService productService = (ProductService) context.getBean("productService");        Product product = new Product();        product.setName("pingguo");        product.setProductId("1");        product.setQuantity(1);        productService.sendProduct(product);        try {            Thread.sleep(60000);        } catch (InterruptedException e) {                    }    }}
springJMSconsumerTopic1  ConsumerApplication.java

package com.npf.test;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext; public class ConsumerApplication {     static final Logger LOG = LoggerFactory.getLogger(ConsumerApplication.class);     @SuppressWarnings({ "resource", "unused" })public static void main(String[] args) {     ApplicationContext context = new ClassPathXmlApplicationContext("spring/applicationContext.xml");        try {            Thread.sleep(60000);        } catch (InterruptedException e) {                   }    } }
springJMSconsumerTopic2  ConsumerApplication.java

package com.npf.test;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext; public class ConsumerApplication {     static final Logger LOG = LoggerFactory.getLogger(ConsumerApplication.class);     @SuppressWarnings({ "resource", "unused" })public static void main(String[] args) {     ApplicationContext context = new ClassPathXmlApplicationContext("spring/applicationContext.xml");        try {            Thread.sleep(60000);        } catch (InterruptedException e) {                   }    } }
Start Application springJMSconsumerTopic1 and Application springJMSconsumerTopic2 first and than start springJMSproducerTopic

and you will see:

springJMSproducerTopic:


springJMSconsumerTopic1 


springJMSconsumerTopic2


springJMSconsumerTopic1 : https://github.com/SpringOrganization/springJMSconsumerTopic1

springJMSconsumerTopic2 : https://github.com/SpringOrganization/springJMSconsumerTopic2

springJMSproducerTopic : https://github.com/SpringOrganization/springJMSproducerTopic



0 0
原创粉丝点击