不为有趣之事,何遣有涯之生
不失其所者久,死而不亡者寿

AMQ简明教程(7) AMQ与Spring结合

AMQ结合spring

Spring提供了对JMS的支持,需要添加Spring支持jms的包,如下:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jms</artifactId>
    <version>4.1.6.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.apache.activemq</groupId>
    <artifactId>activemq-pool</artifactId>
    <version>5.11.1</version>
</dependency>

然后需要在Spring的配置文件中,配置jmsTemplate,示例如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <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://192.168.1.55:61616</value>
                </property>
            </bean>
        </property>
        <property name="maxConnections" value="100"></property>
    </bean>
    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory" ref="jmsFactory" />
        <property name="defaultDestination" ref="destination" />
        <property name="messageConverter">
            <bean class="org.springframework.jms.support.converter.SimpleMessageConverter" />
        </property>
    </bean>
    <bean id="destination" class="org.apache.activemq.command.ActiveMQQueue">
        <constructor-arg index="0" value="spring-queue" />
    </bean>

</beans>

queue消息发送

package com.qiuxm.myweb.service.jms;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

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

/**
 * Created by Administrator on 2015/6/2.
 */

@Service
public class QueueSender {

    @Autowired
    private JmsTemplate jt = null;

    public static void main(String[] args)  throws Exception{
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        QueueSender ct = (QueueSender)ctx.getBean("queueSender");
        ct.jt.send(new MessageCreator() {
            public Message createMessage(Session s) throws JMSException {
                TextMessage msg = s.createTextMessage("Spring msg===");
                return msg;
            }
        });
    }

}

queue消息接收

package com.qiuxm.myweb.service.jms;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;

/**
 * Created by Administrator on 2015/6/2.
 */

@Service
public class QueueReceive {

    @Autowired
    private JmsTemplate jt = null;
    public static void main(String[] args) throws Exception {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        QueueReceive ct = (QueueReceive)ctx.getBean("queueReceive");

        String msg = (String)ct.jt.receiveAndConvert();

        System.out.println("msg==="+msg);
    }
}

如果topic的话,首先需要修改spring的配置:
先添加topic的配置,当然,需要修改jmsTemplate配置里面的defaultDestination,如果不想修改这个配置,那么直接把Destination注入程序,在程序里面选择发送的Destination也可以配置其他的客户端发送和接收跟队列基本是一样的。

如果想要在Spring中配置消费者的话,就不需要再启动接收的客户端了
当然,需要写一个类来实现消息监听
这样测试的时候,只需要启动消息生产者就好了

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <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://192.168.1.55:61616</value>
                </property>
            </bean>
        </property>
        <property name="maxConnections" value="100"></property>
    </bean>
    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory" ref="jmsFactory" />
        <property name="defaultDestination" ref="destinationTopic" />
        <property name="messageConverter">
            <bean class="org.springframework.jms.support.converter.SimpleMessageConverter" />
        </property>
    </bean>

    <bean id="destination" class="org.apache.activemq.command.ActiveMQQueue">
        <constructor-arg index="0" value="spring-queue" />
    </bean>

    <bean id="destinationTopic" class="org.apache.activemq.command.ActiveMQTopic">
        <constructor-arg index="0" value="spring-topic" />
    </bean>

    <bean id="jmsContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
        <property name="connectionFactory" ref="jmsFactory" />
        <property name="destination" ref="destinationTopic" />
        <property name="messageListener" ref="messageListener" />
    </bean>

    <bean id="messageListener"
          class="com.qiuxm.myweb.web.controller.lister.MyMessageListener">
    </bean>

</beans>
package com.qiuxm.myweb.web.controller.lister;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

/**
 * Created by Administrator on 2015/6/2.
 */
public class MyMessageListener implements MessageListener {
    public void onMessage(Message arg0) {
        TextMessage msg = (TextMessage)arg0;
        try {
            System.out.println("receive txt msg==="+msg.getText());
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}

ActiveMQ结合Spring开发最佳实践和建议
1:Camel框架支持大量的企业集成模式,可以大大简化集成组件间的大量服务和复杂的消息流。而Spring框架更注重简单性,仅仅支持基本的最佳实践。

2:Spring消息发送的核心架构是JmsTemplate,隔离了像打开、关闭Session和Producer的繁琐操作,因此应用开发人员仅仅需要关注实际的业务逻辑。但是
JmsTemplate损害了ActiveMQ的PooledConnectionFactory对session和消息producer的缓存机制而带来的性能提升。

3:新的Spring里面,可以设置org.springframework.jms.connection.CachingConnectionFactory的sessionCacheSize ,或者干脆使用ActiveMQ的PooledConnectionFactory

4:不建议使用JmsTemplate的receive()调用,因为在JmsTemplate上的所有调用都是同步的,这意味着调用线程需要被阻塞,直到方法返回,这对性能影响很大

5:请使用DefaultMessageListenerContainer,它允许异步接收消息并缓存session和消息consumer,而且还可以根据消息数量动态的增加或缩减监听器的数量

未经允许不得转载:菡萏如佳人 » AMQ简明教程(7)

欢迎加入极客江湖

进入江湖关于作者