java多線程監聽JMS、MQ隊列

來源:互聯網
上載者:User

      本作品採用知識共用署名-非商業性使用-相同方式共用 2.5 中國大陸許可協議進行許可。

      轉載請註明出處和作者.http://blog.csdn.net/xtj332

背景:訊息佇列中有非常多的訊息需要處理,並且監聽器onMessage()方法中的商務邏輯也相對比較複雜,為了加快隊列訊息的讀取、處理速度。可以通過加快讀取速度和加快處理速度來考慮。因此從這兩個方面都使用多線程來處理。對於訊息處理的業務處理邏輯用線程池來做。對於加快訊息監聽讀取速度可以使用1.使用多個監聽器監聽一個隊列;2.使用一個監聽器開啟多線程監聽。


對於上面提到的方法2使用一個監聽器開啟多線程監聽,藉助spring內建的DefaultMessageListenerContainer可以很方便實現這一功能。

   

<!-- 使用spring進行配置 監聽--><bean id="testListenerContainer1"class="org.springframework.jms.listener.DefaultMessageListenerContainer"><property name="connectionFactory" ref="connectionFactory"></property><property name="destination" ref="queue2"></property><property name="messageListener" ref="messageReceiver"></property><property name="sessionTransacted" value="false"></property><!-- 設定固定的線程數 --><property name="concurrentConsumers" value="6"></property><!-- 設定動態線程數 --><property name="concurrency" value="2-9"></property><!-- 設定最大的線程數 --><property name="maxConcurrentConsumers" value="15"></property></bean>

對於開啟幾個線程可以自行根據需求和效能進行考慮。

     

監聽器列印輸出當前線程:

 public void onMessage(Message message) {        System.out.println("在onMessage中線程ID是"+Thread.currentThread());

輸出結果:

在onMessage中線程ID是Thread[testListenerContainer1-3,5,main]在onMessage中線程ID是Thread[testListenerContainer1-4,5,main]在onMessage中線程ID是Thread[testListenerContainer1-6,5,main]





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.