Integrate ActiveMQ with Spring

Source: Internet
Author: User

Preparations

  1. Download ActiveMQ from the following official website. Version 5.7 is used in this article. The maximum version that can be found in the Maven library when writing blogs is 5.7.

    Http://activemq.apache.org/download-archives.html

  2. Decompress the downloaded file to the directory you want to install

  3. Run activemq. bat in the bin directory to start the ActiveMQ service.

    Broker URL: tcp: // localhost: 61616

    Admin URL: http: // localhost: 8161/admin

  4. Open the Admin URL to view information such as Queue and Topic.

  5. The dependency packages related to ActiveMQ are handed over to the Gradle tool. See the demo configuration.


Basic roles and programming modules of the JMS framework

  • JMS Message Producers: Message producer that provides messages to Message queues.

  • JMS Provider (Broker): a jms Provider, such as ActiveMQ, provides the JMS Queues/Topics service.

  • JMS Message listener/Consumer: receives and uses messages


A jms Provider is like a database. Producer/Consumers needs to connect to the Provider before sending/receiving messages. Similar to establishing a database Connection, JMS ConnectionFactory is responsible for creating a JMS Connection and JMS Connection to create a JMS Session.

  • JMS ConnectionFactory: Producers/Consumers is used to create a connection to the Provider.

  • JMS Connection: encapsulate a Connection to the Provider

  • JMS Session: Message sending and receiving Context

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/140120/223G42096-0.jpg "title =" jms-programmingModel.gif "alt =" wKiom1LXvQrxVnOnAAD304pI3Qk941.jpg "/>

Multiple Queue and topics can be defined on the JMS Provider, and the Queue/Topic to which the producer sends the message. The specific Queue/Topic is Destination.

  • JMS Destination: one-to-one Queue or one-to-many topics

For details about the JMS programming model, refer to the following articles:

Http://docs.oracle.com/javaee/6/tutorial/doc/bnceh.html


Spring integration configuration

  • Queue Message sender (JMS Message Producers ):

ConnectionFactory: used to connect providers and supports connection pool configuration.

JmsTemplate: Spring encapsulation class, which can be used to create, send, and receive messages.

<bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory"    p:brokerURL="tcp://localhost:61616" /><bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">    <constructor-arg name="connectionFactory" ref="connectionFactory" />    <property name="defaultDestinationName" value="TestQueue" /></bean><context:component-scan base-package="com.stevex.demo" />
  • Connection Pool configuration example:

<!-- a pooling based JMS provider -->  <bean id="jmsFactory" class="org.apache.activemq.pool.PooledConnectionFactory" destroy-method="stop">    <property name="connectionFactory">      <bean class="org.apache.activemq.ActiveMQConnectionFactory">        <property name="brokerURL">          <value>tcp://localhost:61616</value>        </property>      </bean>    </property>  </bean>                                                                                                   <!-- Spring JMS Template -->  <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">    <property name="connectionFactory">      <ref local="jmsFactory"/>    </property>  </bean>
  • The receiver of the Queue Message (JMS Message listener ):

ConnectionFactory: used to connect providers and supports connection pool configuration.

Listener: receives messages

Jms: listener-container simplifies the configuration. destination only needs to give the queue/topic name, and no additional definition is required.

<bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory"    p:brokerURL="tcp://localhost:61616" /><jms:listener-container container-type="default"    connection-factory="connectionFactory" acknowledge="auto">    <jms:listener destination="TestQueue" ref="messageListener"        method="onMessage" /></jms:listener-container><bean id="messageListener" class="com.stevex.demo.SimpleMessageListener"/>
  • Topic Message sender (JMS Message Producers ):

ConnectionFactory: used to connect providers and supports connection pool configuration.

JmsTemplate: Spring encapsulation class, which can be used to create, send, and receive messages.

The pubSubDomain attribute value of JmsTemplate is true, indicating that destination is of the Topic type. The default value "false" indicates that destination is of the Queue type.

<bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory"    p:brokerURL="tcp://localhost:61616" /><bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">    <constructor-arg name="connectionFactory" ref="connectionFactory" />    <property name="defaultDestinationName" value="TestTopic" />    <property name="pubSubDomain" value="true" /></bean><context:component-scan base-package="com.stevex.demo" />
  • Topic Message Receiver (JMS Message listener ):

ConnectionFactory: used to connect providers and supports connection pool configuration.

Listener: receives messages

All subscribers can receive messages of the Topic type. This Demo defines two recipients.

Jms: the default value of the destination-type attribute of listener-container is queue. If it is a Topic, it must be specified.

<bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory"    p:brokerURL="tcp://localhost:61616" /><bean id="subscriber1" class="com.stevex.demo.SimpleMessageListener" /><jms:listener-container container-type="default"    destination-type="topic" connection-factory="connectionFactory"    acknowledge="auto">    <jms:listener destination="TestTopic" ref="subscriber1"        method="onMessage" /></jms:listener-container>
  • Producer class implementation code

@Component("messageSender")public class SimpleMessageSender implements MessageSender {    @Autowired    private JmsTemplate jmsTemplate;    @Override    public void sendMessage(final String message) {        jmsTemplate.send(new MessageCreator() {                                                                                                              public Message createMessage(Session session) throws JMSException {                return session.createTextMessage(message);            }                                                                                                          });    }}
  • Listener class implementation code

@Component("messageListener")public class SimpleMessageListener implements MessageListener {    private static final Logger logger = LoggerFactory.getLogger(SimpleMessageListener.class);    public void onMessage(Message message) {        TextMessage textMessage = (TextMessage) message;                                                                                                    try {            logger.info("Message received: " + textMessage.getText());        } catch (JMSException ex) {            logger.error("JMS error", ex);        }    }}

After the application runs, ActiveMQ automatically creates a connection if the requested Queue/Topic does not exist after it receives the connection. We can also send a message to the Listener through the ActiveMQ Admin interface.


This article is from "the power comes from the sincere love !" Blog, please be sure to keep this source http://stevex.blog.51cto.com/4300375/1352334

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.