ActiveMQ結(jié)合Spring

先看application_mq.xml
1.配置ConnectionFactory

<bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory"/>

Spring提供的ConnectionFactory只是Spring用于管理ConnectionFactory的,真正產(chǎn)生到JMS服務(wù)器鏈接的ConnectionFactory還是由ActiveMQ提供,所以完整的ConnectionFactory配置如下,我們以SingleConnectionFactory為例:

<!-- 真正可以產(chǎn)生Connection的ConnectionFactory,由對(duì)應(yīng)的 JMS服務(wù)廠商提供-->  
<bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">  
    <property name="brokerURL" value="tcp://localhost:61616"/>  
</bean> 

<!-- Spring用于管理的ConnectionFactory的ConnectionFactory -->  
<bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">  
    <property name="targetConnectionFactory" ref="targetConnectionFactory"/>  
</bean>  

ActiveMQ為我們提供了一個(gè)PooledConnectionFactory,通過往里面注入一個(gè)ActiveMQConnectionFactory可以用來將ConnectionSession和MessageProducer池化,這樣可以大大的減少我們的資源消耗。當(dāng)使用PooledConnectionFactory時(shí),我們定義一個(gè)ConnectionFactory時(shí)如下:

<!-- 真正可以產(chǎn)生Connection的ConnectionFactory,由對(duì)應(yīng)的 JMS服務(wù)廠商提供-->  
<bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">  
    <property name="brokerURL" value="tcp://localhost:61616"/>  
</bean>  
  
<bean id="pooledConnectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory">
    <property name="connectionFactory" ref="targetConnectionFactory"/>
</bean>
  
<bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">  
    <property name="targetConnectionFactory" ref="pooledConnectionFactory"/>  
</bean>  

2.配置Template和Destination

<!-- 定義JmsTemplate的Queue類型 -->
<bean id="jmsQueueTemplate" class="org.springframework.jms.core.JmsTemplate">
    <!-- 這個(gè)connectionFactory對(duì)應(yīng)的是我們定義的Spring提供的那個(gè)ConnectionFactory對(duì)象 -->
    <constructor-arg ref="connectionFactory" />
    <property name="messageConverter" ref="messageConverter"></property>
    <!-- 非pub/sub模型(發(fā)布/訂閱),即隊(duì)列模式 -->
    <property name="pubSubDomain" value="false" />
</bean>

<!--這個(gè)是隊(duì)列目的地-->
<bean id="queueDestination" class="org.apache.activemq.command.ActiveMQQueue">
    <!-- 設(shè)置消息隊(duì)列的名字 -->
    <constructor-arg index="0" value="HelloWorldSpringQueue" />
</bean>

<!-- 定義JmsTemplate的Topic類型 -->
<bean id="jmsTopicTemplate" class="org.springframework.jms.core.JmsTemplate">
    <constructor-arg ref="connectionFactory" />
    <property name="messageConverter" ref="messageConverter"></property>
    <!-- pub/sub模型(發(fā)布/訂閱) -->
    <property name="pubSubDomain" value="true" />
</bean>

<!--這個(gè)是訂閱目的地-->
<bean id="topicDestination" class="org.apache.activemq.command.ActiveMQTopic">
    <!-- 設(shè)置消息隊(duì)列的名字 -->
    <constructor-arg index="0" value="HelloWorldSpringTopic" />
</bean>

3.配置生產(chǎn)者和消費(fèi)者
我們?cè)谂渲靡粋€(gè)MessageListenerContainer的時(shí)候有三個(gè)屬性必須指定,一個(gè)是表示從哪里監(jiān)聽的ConnectionFactory;一個(gè)是表示監(jiān)聽什么的Destination;一個(gè)是接收到消息以后進(jìn)行消息處理的MessageListener。

<!--send-->
<bean id="queueProducer" class="com.zzhblh.activemq.producer.QueueProducer">
    <property name="jmsQueueTemplate" ref="jmsQueueTemplate"></property>
    <property name="queueDestination" ref="queueDestination"></property>
</bean>

<bean id="topicProducer" class="com.zzhblh.activemq.producer.TopicProducer">
    <property name="jmsTopicTemplate" ref="jmsTopicTemplate"></property>
    <property name="topicDestination" ref="topicDestination"></property>
</bean>

<!--receive-->
<!-- 注入我們自己寫的繼承了javax.jms.MessageListener的消息監(jiān)聽器-->
<bean id="consumerMessageListener" class="com.zzhblh.activemq.consumer.ConsumerMessageListener"/>

<!-- 消息監(jiān)聽容器 -->
<bean id="jmsContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
    <property name="connectionFactory" ref="connectionFactory" />
    <property name="destination" ref="queueDestination" />
    <property name="messageListener" ref="consumerMessageListener" />
    <property name="sessionAcknowledgeMode" value="1"/>//1代表AUTO_ACKNOWLEDGE 
</bean>
<!-- 消息監(jiān)聽容器2 -->
<bean id="jmsContainer2" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
    <property name="connectionFactory" ref="connectionFactory" />
    <property name="destination" ref="topicDestination" />
    <property name="messageListener" ref="consumerMessageListener" />
    <property name="sessionAcknowledgeMode" value="1"/>//1代表AUTO_ACKNOWLEDGE 
</bean>

4.發(fā)送消息

@Service
public class QueueProducer {
    @Autowired
    JmsTemplate jmsQueueTemplate;
    @Autowired
    ActiveMQQueue queueDestination;

    public void sendMessages(final String text, final int i) throws JMSException {
            jmsQueueTemplate.send(queueDestination,new MessageCreator() {
                public Message createMessage(Session session) throws JMSException {
                    TextMessage message = session.createTextMessage(text);
                    message.setIntProperty("messageCount", i);
                    return message;
                }
            });
    }

    public JmsTemplate getJmsQueueTemplate() {
        return jmsQueueTemplate;
    }

    public void setJmsQueueTemplate(JmsTemplate jmsQueueTemplate) {
        this.jmsQueueTemplate = jmsQueueTemplate;
    }

    public ActiveMQQueue getQueueDestination() {
        return queueDestination;
    }

    public void setQueueDestination(ActiveMQQueue queueDestination) {
        this.queueDestination = queueDestination;
    }
}

5.接收消息

public class ConsumerMessageListener implements MessageListener {
    private NotifyMessageConverter messageConverter;

    @Override
    public void onMessage(Message message) {
        if (message instanceof TextMessage) {
            //這里我們知道生產(chǎn)者發(fā)送的就是一個(gè)純文本消息,所以這里可以直接進(jìn)行強(qiáng)制轉(zhuǎn)換,或者直接把onMessage方法的參數(shù)改成Message的子類TextMessage
            TextMessage textMsg = (TextMessage) message;
            System.out.println("接收到一個(gè)純文本消息。");
            try {
                System.out.println("消息內(nèi)容是:" + textMsg.getText());
            } catch (JMSException e) {
                e.printStackTrace();
            }
        } else if (message instanceof MapMessage) {
            MapMessage mapMessage = (MapMessage) message;
        } else if (message instanceof ObjectMessage) {
            ObjectMessage objMessage = (ObjectMessage) message;
            try {
                /*Object obj = objMessage.getObject();
                Email email = (Email) obj;
                Email email = (Email) messageConverter.fromMessage(objMessage);
                System.out.println("接收到一個(gè)ObjectMessage,包含Email對(duì)象。");
                System.out.println(email);*/
                messageConverter.fromMessage(message);
                System.out.println("接收到一個(gè)ObjectMessage");
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
    }
}

6.消息轉(zhuǎn)換器

public class NotifyMessageConverter implements MessageConverter {
    @Override
    public Message toMessage(Object object, Session session) throws JMSException, MessageConversionException {
        return session.createObjectMessage((Serializable) object);
    }

    @Override
    public Object fromMessage(Message message) throws JMSException, MessageConversionException {
        ObjectMessage objMessage = (ObjectMessage) message;
        return objMessage.getObject();
    }
}

要點(diǎn):
1.用activemq的connection構(gòu)造spring用于管理的SingleConnectionFactory。用于發(fā)送/接收消息。
2.創(chuàng)建Destination,ActiveMQQueue或ActiveMQTopic。用于發(fā)送/接收消息。

3.用SingleConnectionFactory構(gòu)造JmsTemplate。用于發(fā)送消息。
4.用JmsTemplate和Destination(ActiveMQQueue/ActiveMQTopic)構(gòu)造QueueProducer/TopicProducer。用于發(fā)送消息。

5.創(chuàng)建MessageListener。用于接收消息。
6.構(gòu)造ListenerContainer,用到ConnectionFactory,Destination,MessageListener。用于接收消息。


參考:
http://my.oschina.net/xiaoxishan/blog/381209
http://shengwangi.blogspot.com/2015/06/spring-jms-with-activemq-hello-world.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容