spring整合activemq發送消息[queue類型]實例

http://www.tuicool.com/articles/FVf26b

queue類型消息

pom依賴

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.11</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.apache.activemq</groupId>
  <artifactId>activemq-all</artifactId>
  <version>5.11.1</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-jms</artifactId>
  <version>4.1.4.RELEASE</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-test</artifactId>
  <version>4.1.4.RELEASE</version>
</dependency>

1、配置文件

<?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">
  <!-- 配置JMS連接工廠 -->
  <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
    <property name="brokerURL" value="failover:(tcp://192.168.147.131:61616)" />
  </bean>
  <!-- 定義消息隊列(Queue) -->
  <bean id="queueDestination" class="org.apache.activemq.command.ActiveMQQueue">
    <!-- 設置消息隊列的名字 -->
    <constructor-arg>
      <value>testSpringQueue</value>
    </constructor-arg>
  </bean>
  <!-- 配置JMS模板(Queue),Spring提供的JMS工具類,它發送、接收消息。 -->
  <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
    <property name="connectionFactory" ref="connectionFactory" />
    <property name="defaultDestination" ref="queueDestination" />
    <property name="receiveTimeout" value="10000" />
  </bean>
</beans>

2、生產者代碼

package com.mq.spring.queue;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
import javax.jms.*;
/**
 * created on 2015/6/4
 * @author [email protected]
 * @version 1.0
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring-mq-queue.xml"})
public class QueueSender {
  @Resource
  private JmsTemplate jmsTemplate;
  @Test
  public void send(){
    sendMqMessage(null,"spring activemq queue type message !");
  }
  /**
   * 說明:發送的時候如果這裏沒有顯示的指定destination.將用spring xml中配置的destination
   * @param destination
   * @param message
   */
  public void sendMqMessage(Destination destination, final String message){
    if(null == destination){
      destination = jmsTemplate.getDefaultDestination();
    }
    jmsTemplate.send(destination, new MessageCreator() {
      public Message createMessage(Session session) throws JMSException {
        return session.createTextMessage(message);
      }
    });
    System.out.println("spring send message...");
  }
  public void setJmsTemplate(JmsTemplate jmsTemplate) {
    this.jmsTemplate = jmsTemplate;
  }
}

3、消費者代碼

package com.mq.spring.queue;
import org.junit.Test;
import javax.jms.*;
import org.junit.runner.RunWith;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
import javax.jms.Message;
/**
 * created on 2015/6/4
 * @author [email protected]
 * @version 1.0
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring-mq-queue.xml"})
public class QueueReceiver {
  @Resource
  private JmsTemplate jmsTemplate;
  @Test
  public void receiveMqMessage(){
    Destination destination = jmsTemplate.getDefaultDestination();
    receive(destination);
  }
  /**
   * 接受消息
   */
  public void receive(Destination destination) {
    TextMessage tm = (TextMessage) jmsTemplate.receive(destination);
    try {
      System.out.println("從隊列" + destination.toString() + "收到了消息:\t" + tm.getText());
    } catch (JMSException e) {
      e.printStackTrace();
    }
  }
  public void setJmsTemplate(JmsTemplate jmsTemplate) {
    this.jmsTemplate = jmsTemplate;
  }
}

程序運行結果:

說明:上面的生產者和消費者使用同一套配置文件,使用獨立的程序去接收消息,spring jms也提供了消息監聽處理.接下來我們換成監聽式消費

配置文件如下:

<?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">
  <!-- 配置JMS連接工廠 -->
  <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
    <property name="brokerURL" value="failover:(tcp://192.168.147.131:61616)" />
  </bean>
  <!-- 定義消息隊列(Queue) -->
  <bean id="queueDestination" class="org.apache.activemq.command.ActiveMQQueue">
    <!-- 設置消息隊列的名字 -->
    <constructor-arg>
      <value>testSpringQueue</value>
    </constructor-arg>
  </bean>
  <!-- 配置消息隊列監聽者(Queue) -->
  <bean id="consumerMessageListener" class="com.mq.spring.queue.ConsumerMessageListener" />
  <!-- 消息監聽容器(Queue),配置連接工廠,監聽的隊列是testSpringQueue,監聽器是上面定義的監聽器 -->
  <bean id="jmsContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
    <property name="connectionFactory" ref="connectionFactory" />
    <property name="destination" ref="queueDestination" />
    <property name="messageListener" ref="consumerMessageListener" />
  </bean>
</beans>

這樣我們的消息消費就可以在監聽器中處理消費了.生產的代碼不變,修改發送者的消息體內容,執行生產程序.可以看到運行效果如下:

關於springjms消息監聽器,查看: http://haohaoxuexi.iteye.com/blog/1893676

Topic類型消息

在使用 Spring JMS的時候,主題( Topic)和隊列消息的主要差異體現在 JmsTemplate中 "pubSubDomain"是否設置爲 True。如果爲 True,則是 Topic;如果是 false或者默認,則是 queue。

<property name="pubSubDomain" value="true" />

topic類型消費配置文件說明

<?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">
  <!-- 配置JMS連接工廠 -->
  <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
    <property name="brokerURL" value="failover:(tcp://192.168.147.131:61616)" />
  </bean>
  <!-- 定義消息Destination -->
  <bean id="destination" class="org.apache.activemq.command.ActiveMQQueue">
    <!-- 設置消息隊列的名字 -->
    <constructor-arg>
      <value>testSpringTopic</value>
    </constructor-arg>
  </bean>
  <!-- 配置JMS模板(Queue),Spring提供的JMS工具類,它發送、接收消息。 -->
  <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
    <property name="connectionFactory" ref="connectionFactory" />
    <property name="defaultDestination" ref="destination" />
    <property name="receiveTimeout" value="10000" />
  </bean>
  <!-- 配置消息消費監聽者 -->
  <bean id="consumerMessageListener" class="com.mq.spring.topic.ConsumerMessageListener" />
  <!-- 消息監聽容器,配置連接工廠,監聽器是上面定義的監聽器 -->
  <bean id="jmsContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
    <property name="connectionFactory" ref="connectionFactory" />
    <property name="destination" ref="destination" />
    <!--主題(Topic)和隊列消息的主要差異體現在JmsTemplate中"pubSubDomain"是否設置爲True。如果爲True,則是Topic;如果是false或者默認,則是queue-->
    <property name="pubSubDomain" value="true" />
    <property name="messageListener" ref="consumerMessageListener" />
  </bean>
</beans>

生產者代碼:

package com.mq.spring.topic;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
/**
 * created on 2015/6/4
 * @author [email protected]
 * @version 1.0
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring-mq-topic.xml"})
public class TopicSender {
  @Resource
  private JmsTemplate jmsTemplate;
  @Test
  public void send(){
    sendMqMessage(null,"spring activemq topic type message[with listener] !");
  }
  /**
   * 說明:發送的時候如果這裏沒有顯示的指定destination.將用spring xml中配置的destination
   * @param destination
   * @param message
   */
  public void sendMqMessage(Destination destination, final String message){
    if(null == destination){
      destination = jmsTemplate.getDefaultDestination();
    }
    jmsTemplate.send(destination, new MessageCreator() {
      public Message createMessage(Session session) throws JMSException {
        return session.createTextMessage(message);
      }
    });
    System.out.println("spring send message...");
  }
  public void setJmsTemplate(JmsTemplate jmsTemplate) {
    this.jmsTemplate = jmsTemplate;
  }
}
View Code

監聽器代碼:

public class ConsumerMessageListener implements MessageListener{
  @Override
  public void onMessage(Message message) {
    TextMessage tm = (TextMessage) message;
    try {
      System.out.println("ConsumerMessageListener收到了文本消息:\t" + tm.getText());
    } catch (JMSException e) {
      e.printStackTrace();
    }
  }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章