Java訊息佇列-Spring整合ActiveMq

來源:互聯網
上載者:User

標籤:config   2.0   程式   command   系統   container   接收   找不到   2.3   

1、概述 

  首先和大家一起回顧一下Java Message Service,在我之前的部落格《Java訊息佇列-JMS概述》中,我為大家分析了:

  1. Message Service:一個中介軟體,用於解決兩個活多個程式之間的耦合,底層由Java 實現。
  2. 優勢:非同步、可靠
  3. 訊息模型:點對點,發布/訂閱
  4. JMS中的對象

  然後在另一篇部落格《Java訊息佇列-ActiveMq實戰》中,和大家一起從0到1的開啟了一個ActiveMq 的項目,在項目開發的過程中,我們對ActiveMq有了一定的瞭解:  

  1. 多種語言和協議編寫用戶端。語言: Java, C, C++, C#, Ruby, Perl, Python, PHP。應用協議: OpenWire,Stomp REST,WS Notification,XMPP,AMQP
  2. 完全支援JMS1.1和J2EE 1.4規範 (持久化,XA訊息,事務)
  3. 對Spring的支援,ActiveMQ可以很容易內嵌到使用Spring的系統裡面去,而且也支援Spring2.0的特性
  4. 通過了常見J2EE伺服器(如 Geronimo,JBoss 4, GlassFish,WebLogic)的測試,其中通過JCA 1.5 resource adaptors的配置,可以讓ActiveMQ可以自動的部署到任何相容J2EE 1.4 商務服務器上
  5. 支援多種傳送協議:in-VM,TCP,SSL,NIO,UDP,JGroups,JXTA
  6. 支援通過JDBC和journal提供高速的訊息持久化
  7. 從設計上保證了高效能的叢集,用戶端-伺服器,點對點
  8. 支援Ajax
  9. 支援與Axis的整合
  10. 可以很容易得調用內嵌JMS provider,進行測試

  在接下來的這篇部落格中,我會和大家一起來整合Spring 和ActiveMq,這篇博文,我們基於Spring+JMS+ActiveMQ+Tomcat,實現了Point-To-Point的非同步隊列訊息和PUB/SUB(發布/訂閱)模型,簡單一實例,不包含任何業務。

 

2、目錄結構

 

  2.1 項目目錄

      IDE選擇了IDEA(建議大家使用),為了避免下載jar 的各種麻煩,底層使用maven搭建了一個項目,整合了Spring 和ActiveMq

   

   

    2.2 pom.xml View Code

    因為這裡pom.xml 檔案有點長,就不展開了。

    我們可以看到其實依賴也就幾個,1、Spring 核心依賴 2、ActiveMq core和pool(這裡如果同學們選擇匯入jar,可以直接匯入我們上一篇部落格中說道的那個activemq-all 這個jar包)3、java servlet 相關依賴

    這裡面我們選擇的ActiveMq pool 的依賴版本會和之後的dtd 有關係,需要版本對應,所以同學們等下配置activemq 檔案的時候,需要注意dtd 版本選擇

 

    2.3 web.xml

    web.xml 也大同小異,指定Spring 設定檔,springMvc 命名,編碼格式

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns="http://java.sun.com/xml/ns/javaee"         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee          http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"         version="3.0">  <display-name>Archetype Created Web Application</display-name>  <!-- 載入spring的設定檔,例如hibernate、jms等整合 -->  <context-param>    <param-name>contextConfigLocation</param-name>    <param-value>      classpath:applicationContext*.xml;    </param-value>  </context-param>  <listener>    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  </listener>  <servlet>    <servlet-name>springMVC</servlet-name>    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    <init-param>      <param-name>contextConfigLocation</param-name>      <param-value>classpath:spring-mvc.xml</param-value>    </init-param>    <load-on-startup>1</load-on-startup>  </servlet>  <servlet-mapping>    <servlet-name>springMVC</servlet-name>    <url-pattern>/</url-pattern>  </servlet-mapping>  <!-- 處理編碼格式 -->  <filter>    <filter-name>characterEncodingFilter</filter-name>    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>    <init-param>      <param-name>encoding</param-name>      <param-value>UTF-8</param-value>    </init-param>    <init-param>      <param-name>forceEncoding</param-name>      <param-value>true</param-value>    </init-param>  </filter>  <filter-mapping>    <filter-name>characterEncodingFilter</filter-name>    <url-pattern>/*</url-pattern>  </filter-mapping></web-app>

 

 

    2.4 SpringMvc 和applicationContext.xml

      這裡面的SpringMVC沒什麼特別,有需要的同學可以參考一下:

 View Code

      applicationContext.xml 主要使用來裝載Bean,我們項目中並沒有什麼特別的Java Bean,因此只用來指出包掃描路徑:

 View Code

 

   

    2.5 applicationContext-ActiveMQ.xml
<?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:amq="http://activemq.apache.org/schema/core"       xmlns:jms="http://www.springframework.org/schema/jms"       xmlns:context="http://www.springframework.org/schema/context"       xmlns:mvc="http://www.springframework.org/schema/mvc"       xsi:schemaLocation="        http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans-4.1.xsd        http://www.springframework.org/schema/context        http://www.springframework.org/schema/context/spring-context-4.1.xsd        http://www.springframework.org/schema/mvc        http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd        http://www.springframework.org/schema/jms        http://www.springframework.org/schema/jms/spring-jms-4.1.xsd        http://activemq.apache.org/schema/core        http://activemq.apache.org/schema/core/activemq-core-5.12.1.xsd">    <context:component-scan base-package="com.Jayce" />    <mvc:annotation-driven />    <amq:connectionFactory id="amqConnectionFactory"                           brokerURL="tcp://192.168.148.128:61616"                           userName="admin"                           password="admin" />    <!-- 配置JMS串連工長 -->    <bean id="connectionFactory"          class="org.springframework.jms.connection.CachingConnectionFactory">        <constructor-arg ref="amqConnectionFactory" />        <property name="sessionCacheSize" value="100" />    </bean>    <!-- 定義訊息佇列(Queue) -->    <bean id="demoQueueDestination" class="org.apache.activemq.command.ActiveMQQueue">        <!-- 設定訊息佇列的名字 -->        <constructor-arg>            <value>Jaycekon</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="demoQueueDestination" />        <property name="receiveTimeout" value="10000" />        <!-- true是topic,false是queue,預設是false,此處顯示寫出false -->        <property name="pubSubDomain" value="false" />    </bean>    <!-- 配置訊息佇列監聽者(Queue) -->    <bean id="queueMessageListener" class="com.Jayce.Filter.QueueMessageListener" />    <!-- 顯示注入訊息監聽容器(Queue),配置串連工廠,監聽的目標是demoQueueDestination,監聽器是上面定義的監聽器 -->    <bean id="queueListenerContainer"          class="org.springframework.jms.listener.DefaultMessageListenerContainer">        <property name="connectionFactory" ref="connectionFactory" />        <property name="destination" ref="demoQueueDestination" />        <property name="messageListener" ref="queueMessageListener" />    </bean></beans>

 

       這裡和大家講解一下這個設定檔,如果大家能夠從上述設定檔中看懂,可以跳過。同學們也可以在ActiveMQ官網中的查看。

       1、ActiveMq 中的DTD,我們在聲明相關配置之前,我們需要先匯入ActiveMq 中的DTD,不然Spring 並不理解我們的標籤是什麼意思。

         http://activemq.apache.org/schema/core/activemq-core-5.12.1.xsd

        我們在pom.xml 檔案中有配置了activemq 的版本依賴我們這裡的版本,需要和依賴的版本一樣,不然是找不到相關的dtd

       2、amq:connectionFactory:很直白的一個配置項,用於配置我們連結工廠的地址和使用者名稱密碼,這裡需要注意的是選擇tcp串連而不是http串連

       3、jmsTemplate:比較重要的一個配置,這裡指定了串連工廠,預設訊息發送目的地,還有串連時間長度,發布訊息的方式

 

3、項目結構  3.1 ProducerService
package com.Jayce.Service;import org.springframework.jms.core.JmsTemplate;import org.springframework.jms.core.MessageCreator;import org.springframework.stereotype.Service;import javax.annotation.Resource;import javax.jms.Destination;import javax.jms.JMSException;import javax.jms.Message;import javax.jms.Session;/** * Created by Administrator on 2017/1/5. */@Servicepublic class ProducerService {    @Resource(name="jmsTemplate")    private JmsTemplate jmsTemplate;    public void sendMessage(Destination destination,final String msg){        System.out.println(Thread.currentThread().getName()+" 向隊列"+destination.toString()+"發送訊息---------------------->"+msg);        jmsTemplate.send(destination, new MessageCreator() {            public Message createMessage(Session session) throws JMSException {                return session.createTextMessage(msg);            }        });    }    public void sendMessage(final String msg){        String destination = jmsTemplate.getDefaultDestinationName();        System.out.println(Thread.currentThread().getName()+" 向隊列"+destination+"發送訊息---------------------->"+msg);        jmsTemplate.send(new MessageCreator() {            public Message createMessage(Session session) throws JMSException {                return session.createTextMessage(msg);            }        });    }}

 

     將訊息生產者做成一個服務,當我們需要發送訊息的時候,只需要調用ProducerService執行個體中的sendMessage 方法就可以向預設目的發送一個訊息。

    這裡提供了兩個發送方式,一個是發送到預設的目的地,一個是根據目的地發送訊息。

    有興趣的同學可以和我上一篇文章《ActiveMq實戰》中ActiveMq 發送訊息的方式對比一下,可以發現一些不同。

 

 

   3.2 ConsumerService
package com.Jayce.Service;import org.springframework.jms.core.JmsTemplate;import org.springframework.stereotype.Service;import javax.annotation.Resource;import javax.jms.Destination;import javax.jms.JMSException;import javax.jms.TextMessage;/** * Created by Administrator on 2017/1/5. */@Servicepublic class ConsumerService {    @Resource(name="jmsTemplate")    private JmsTemplate jmsTemplate;    public TextMessage receive(Destination destination){        TextMessage textMessage = (TextMessage) jmsTemplate.receive(destination);        try{            System.out.println("從隊列" + destination.toString() + "收到了訊息:\t"                    + textMessage.getText());        } catch (JMSException e) {            e.printStackTrace();        }        return textMessage;    }}

 

 

     因為我們項目中並沒有什麼業務,所以的話對訊息的處理也就是列印輸出。我們只需要調用jmsTemplate中的 receive 方法,就可以從裡面擷取到一條訊息。

     再和我們上一篇部落格對比一下,上一篇部落格中,我們接受到資訊之後需要手動確認事務,這樣ActiveMQ中才會確定這條訊息已經被正確讀取了。而整合了Spring之後,事務將由Spring 來管理。

 

   3.3 MessageController
package com.Jayce.Controller;import com.Jayce.Service.ConsumerService;import com.Jayce.Service.ProducerService;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.ResponseBody;import javax.annotation.Resource;import javax.jms.Destination;import javax.jms.TextMessage;/** * Created by Administrator on 2017/1/5. */@Controllerpublic class MessageController {    private Logger logger = LoggerFactory.getLogger(MessageController.class);    @Resource(name = "demoQueueDestination")    private Destination destination;    //隊列訊息生產者    @Resource(name = "producerService")    private ProducerService producer;    //隊列訊息消費者    @Resource(name = "consumerService")    private ConsumerService consumer;    @RequestMapping(value = "/SendMessage", method = RequestMethod.POST)    @ResponseBody    public void send(String msg) {        logger.info(Thread.currentThread().getName()+"------------send to jms Start");        producer.sendMessage(msg);        logger.info(Thread.currentThread().getName()+"------------send to jms End");    }    @RequestMapping(value= "/ReceiveMessage",method = RequestMethod.GET)    @ResponseBody    public Object receive(){        logger.info(Thread.currentThread().getName()+"------------receive from jms Start");        TextMessage tm = consumer.receive(destination);        logger.info(Thread.currentThread().getName()+"------------receive from jms End");        return tm;    }}

    控制層裡面需要注入我們的生產者和消費者(實際開發中,生產者和消費者肯定不會在同一個項目中的,不然就Message Service這個東西就沒有意義了)。

    現在服務層和控制層都好了,接下來我們就進行一個簡單的測試

 

4、項目測試  4.1 啟動ActiveMq

      先確定你的ActiveMQ服務已經開啟。

    

 

 

  4.2 啟動項目

    項目使用了Tomcat 外掛程式,避免了本地再下載Tomcat的麻煩,有需要的同學可以使用一下。

<plugins>      <plugin>        <groupId>org.apache.tomcat.maven</groupId>        <artifactId>tomcat7-maven-plugin</artifactId>        <configuration>          <port>8080</port>          <path>/</path>        </configuration>      </plugin></plugins>

 

 

 

  4.3 發送訊息

  這裡用了Chrome 的一個外掛程式PostMan 有興趣的同學可以瞭解一下,在Chrome 拓展程式中可以找到,避免了後端的同學去弄頁面!

    

    我們發送了一個post 請求之後,看一下伺服器的效果:

    我們可以看到,已經向隊列發送了一條訊息。我們看一下ActiveMq現在的狀態:

    我們可以看到,一條訊息已經成功發送到了ActiveMq中。

 

 

  4.4 接收訊息

    使用get請求訪問伺服器後台:

  

 

     服務的輸出:

 

     ActiveMq伺服器狀態:

    我們可以看到,消費者已經消費了一條資訊,並且沒有斷開與ActiveMq之間的連結。

  

  4.5 監聽器

    在實際項目中,我們很少會自己手動去擷取訊息,如果需要手動去擷取訊息,那就沒有必要使用到ActiveMq了,可以用一個Redis 就足夠了。

    不能手動去擷取訊息,那麼我們就可以選擇使用一個監聽器來監聽是否有訊息到達,這樣子可以很快的完成對訊息的處理。

   4.5.1 applicationContext-ActiveMQ.xml 配置

      在上面的設定檔中,我們已經預設的添加了這段監聽器的設定檔,如果同學們不想使用這個監聽器,可以直接注釋掉。

    <!-- 配置訊息佇列監聽者(Queue) -->    <bean id="queueMessageListener" class="com.Jayce.Filter.QueueMessageListener" />    <!-- 顯示注入訊息監聽容器(Queue),配置串連工廠,監聽的目標是demoQueueDestination,監聽器是上面定義的監聽器 -->    <bean id="queueListenerContainer"          class="org.springframework.jms.listener.DefaultMessageListenerContainer">        <property name="connectionFactory" ref="connectionFactory" />        <property name="destination" ref="demoQueueDestination" />        <property name="messageListener" ref="queueMessageListener" />    </bean>

 

 

   4.5.2 MessageListener

      我們需要建立一個類實現MessageListener 介面:

package com.Jayce.Filter;import javax.jms.JMSException;import javax.jms.Message;import javax.jms.MessageListener;import javax.jms.TextMessage;/** * Created by Administrator on 2017/1/5. */public class QueueMessageListener implements MessageListener {    public void onMessage(Message message) {        TextMessage tm = (TextMessage) message;        try {            System.out.println("QueueMessageListener監聽到了簡訊:\t"                    + tm.getText());            //do something ...        } catch (JMSException e) {            e.printStackTrace();        }    }}

 

   實現介面的onMessage 方法,我們將需要的業務操作在裡面解決,這樣子,就完成了我們生產者-中介軟體-消費者,這樣一個解耦的操作了。 

 

   4.5.3 測試

    和上面一樣,使用postMan 發送post請求,我們可以看到控制台裡面,訊息馬上就能列印出來:

   

    再看看ActiveMQ伺服器的狀態:

  我們可以看到,使用監聽器的效果,和手動接收訊息的效果是一樣的。

  這樣子一整個項目下來,我們已經成功的整合了Spring和ActiveMQ。

 

  4.6 壓力測試

    這裡其實也算不上什麼壓力測試,在配置pom.xml檔案的時候,大家有看到一個 commons-httpclient 的依賴,接下來我們使用httpClient 不停的想伺服器發送訊息,看一下伺服器解決訊息的速度如何:

package com.Jaycekon.test;import org.apache.commons.httpclient.HttpClient;import org.apache.commons.httpclient.methods.PostMethod;import org.junit.Test;import java.io.IOException;import java.util.concurrent.atomic.AtomicInteger;/** * Created by Administrator on 2017/1/5. */public class Client {    @Test    public void test() {        HttpClient httpClient = new HttpClient();        new Thread(new Sender(httpClient)).start();    }}class Sender implements Runnable {    public static AtomicInteger count = new AtomicInteger(0);    HttpClient httpClient;    public Sender(HttpClient client) {        httpClient = client;    }    public void run() {            try {                System.out.println(Thread.currentThread().getName()+"---Send message-"+count.getAndIncrement());                PostMethod post = new PostMethod("http://127.0.0.1:8080/SendMessage");                post.addParameter("msg", "Hello world!");                httpClient.executeMethod(post);                System.out.println(Thread.currentThread().getName()+"---Send message Success-"+count.getAndIncrement());            } catch (IOException e) {                e.printStackTrace();            }        }    }

 

     這裡面用了HttpClient 來向伺服器發送Post 請求,然後計數輸出,有興趣的同學可以自己測試一下,可以多開幾個線程,這裡只開了一個線程。

Java訊息佇列-Spring整合ActiveMq

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.