RabbitMQ的介紹與spring整合


本文主要講述的是個人參考官網及其他前輩博客,對RabbitMQ的一些理解與spring整個RabbitMQ.

一、RabbitMQ的介紹

1.1、什么是RabbitMQ

RabbitMQ是一個由erlang開發的AMQP(Advanced Message Queue )的開源實現,官網地址http://www.rabbitmq.com

1.2、什么是AMQP

AMQP就是一個協議,是一個高級抽象層消息通信協議。

雖然在同步消息通訊的世界里有很多公開標准(如 COBAR的 IIOP ,或者是 SOAP 等),但是在異步消息處理中卻不是這樣,只有大企業有一些商業實現(如微軟的 MSMQ ,IBM 的 Websphere MQ 等),因此,在 2006 年的 6 月,Cisco 、Redhat、iMatix 等聯合制定了 AMQP 的公開標准。也就是說AMQP是異步通訊的一個協議。

1.3、介紹幾個常說的名詞

Server(broker:代理):接受客戶端連接,實現AMQP消息隊列和路由功能的進程。

Virtual Host:其實是一個虛擬概念,類似於權限控制組,一個Virtual Host里面可以有若干個Exchange和Queue,但是權限控制的最小粒度是Virtual Host

connection:連接,對於RabbitMQ而言,其實就是一個位於客戶端和Broker之間的TCP連接。

channel:信道,僅僅創建了客戶端到Broker之間的連接后,客戶端還是不能發送消息的。需要為每一個Connection創建Channel,AMQP協議規定只有通過Channel才能執行AMQP的命令。一個Connection可以包含多個Channel。之所以需要Channel,是因為TCP連接的建立和釋放都是十分昂貴的,如果一個客戶端每一個線程都需要與Broker交互,如果每一個線程都建立一個TCP連接,暫且不考慮TCP連接是否浪費,就算操作系統也無法承受每秒建立如此多的TCP連接。RabbitMQ建議客戶端線程之間不要共用Channel,至少要保證共用Channel的線程發送消息必須是串行的,但是建議盡量共用Connection。

Exchange:接受生產者發送的消息,並根據Binding規則將消息路由給服務器中的隊列。ExchangeType決定了Exchange路由消息的行為,例如,在RabbitMQ中,ExchangeType有direct、Fanout和Topic三種,不同類型的Exchange路由的行為是不一樣的。

Queue: 由Header和Body組成,Header是由生產者添加的各種屬性的集合,包括Message是否被持久化、由哪個Message Queue接受、優先級是多少等。而Body是真正需要傳輸的APP數據

Message Queue:消息隊列,用於存儲還未被消費者消費的消息

Binding:Binding聯系了Exchange與Message Queue。Exchange在與多個Message Queue發生Binding后會生成一張路由表,路由表中存儲着Message Queue所需消息的限制條件即Binding Key。當Exchange收到Message時會解析其Header得到Routing Key,Exchange根據Routing Key與Exchange Type將Message路由到Message Queue。Binding Key由Consumer在Binding Exchange與Message Queue時指定,而Routing Key由Producer發送Message時指定,兩者的匹配方式由Exchange Type決定。 

 二、RabbitMQ的使用場景

關於RabbitMQ的幾種使用場景,這里都是根據官網https://www.rabbitmq.com/getstarted.html來的,具體的代碼實現,這里就不粘, 簡單總結一下。

2.1 簡單模式

一個生產者、一個消費者,生產者直接將消息發送到隊列,消費者消費消息

2.2 工人之間分配模式

一個生產者、兩個消費者,生產者將消息直接發送到隊列,消費者消費消息

注意:

在消費者代碼里沒有這個設置的話channel.basicQos(1),是平均分配, 加上這個設置,就是能者多勞,這種更加符合實際的應用場景;

2.3 訂閱模式

一個生產者、多個消費者,生產者將消息發送到Exchange中,消費者通過路由規則接受消息

有三種類型的Exchanges:direct, fanout,topic。 每個實現了不同的路由算法(routing algorithm)。

· Direct exchange:如果 routing key 匹配, 那么Message就會被傳遞到相應的queue中。其實在queue創建時,它會自動的以queue的名字作為routing key來綁定那個exchange。

·Fanout exchange: 會向響應的queue廣播【沒有路由規則】。

·Topic exchange: 對key進行模式匹配,比如ab*可以傳遞到所有ab*的queue。

2.4 RPC模式

這塊還在學習中,后續補充......

三、spring整合RabbitMQ

3.1添加依賴

<dependency>
	 <groupId>org.springframework.amqp</groupId>
	 <artifactId>spring-rabbit</artifactId>
         <version>1.4.0.RELEASE</version>
 </dependency>
 <dependency>
	<groupId>com.rabbitmq</groupId>
	<artifactId>amqp-client</artifactId>
	<version>3.4.1</version>
</dependency>    

3.2 新增spring-rabbitmq.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:rabbit="http://www.springframework.org/schema/rabbit" 
    xmlns:context="http://www.springframework.org/schema/context"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
    http://www.springframework.org/schema/rabbit
    http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd" >

    <description>rabbitmq 連接服務配置</description>
    
   <!--  <context:property-placeholder location="classpath:rabbitMQ.properties" /> -->  
    
    <!-- 連接配置 -->
    <rabbit:connection-factory id="connectionFactory" host="${mq.host}" username="${mq.username}" password="${mq.password}" port="${mq.port}"  virtual-host="${mq.vhost}"/>
    
    <rabbit:admin connection-factory="connectionFactory"/>

    <!-- spring template聲明-->
    <rabbit:template exchange="test-mq-exchange" id="amqpTemplate"  connection-factory="connectionFactory"  />
	<!-- message-converter="jsonMessageConverter" -->

    <!-- 消息對象json轉換類 -->
    <!-- <bean id="jsonMessageConverter" class="org.springframework.amqp.support.converter.Jackson2JsonMessageConverter" /> -->
    
    <!-- 聲明一個Que -->
    <rabbit:queue id="test_queue" name="test_queue" durable="true" auto-delete="false" exclusive="false" />
    <!-- 
    durable:是否持久化
	exclusive: 僅創建者可以使用的私有隊列,斷開后自動刪除
	auto_delete: 當所有消費客戶端連接斷開后,是否自動刪除隊列
     -->  
     
     <!-- 聲明一個Exchange -->
    <rabbit:direct-exchange name="test-mq-exchange" durable="true" auto-delete="false" id="test-mq-exchange">
	    <rabbit:bindings>
	        <rabbit:binding queue="test_queue" key="test_queue"/>
	    </rabbit:bindings>
	</rabbit:direct-exchange>
	<!-- 
	rabbit:direct-exchange:定義exchange模式為direct,意思就是消息與一個特定的路由鍵完全匹配,才會轉發。 
	rabbit:binding:設置消息queue匹配的key
	-->
	
	
</beans>

3.3 rabbitMQ.properties內容

mq.host=127.0.0.1
mq.username=root
mq.password=root
mq.port=5672
#虛擬主機
mq.vhost=/test-vhost

3.4接口與實現類

//接口
public interface MQProducer 
{
	/**
     * 發送消息到指定隊列
     * @param queueKey
     * @param object
     */
    public void sendDataToQueue(String queueKey, Object object);
}

//實現類

@Service
public class MQProducerImpl implements MQProducer 
{
	
    @Autowired
    private AmqpTemplate amqpTemplate;

    private final static Logger LOGGER = Logger.getLogger(MQProducerImpl.class);
    
    public void sendDataToQueue(String queueKey, Object object) 
    {
        try 
        {
        	LOGGER.info("=========發送消息開始=============消息:"+object.toString());
            amqpTemplate.convertAndSend(queueKey, object);
        } 
        catch (Exception e) 
        {
            LOGGER.error(e);
        }

    }
}

3.5 隊列監聽

@Component
public class QueueListenter implements MessageListener
{

    public void onMessage(Message message) 
    {
    	String str = "";
        try
        {
        	str = new String(message.getBody(), "UTF-8");
        	System.out.println("=============監聽【QueueListenter】消息"+message);
            System.out.print("=====獲取消息"+str);
            
        }catch(Exception e)
        {
            e.printStackTrace();
        }
    }

}

3.6 配置監聽器

<!-- 監聽器的bean -->

<bean id="queueListenter" class="com.yh.showpic.rabbitmq.listener.QueueListenter"/>
<!-- 配置監聽queue -->
<rabbit:listener-container connection-factory="connectionFactory" acknowledge="auto">
    	<rabbit:listener queues="test_queue" ref="queueListenter"/>
</rabbit:listener-container>

3.7 測試類

@RunWith(value = SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/spring/spring.xml","classpath:/spring/spring-rabbitMQ.xml"})
public class TestQueue
{
    @Autowired
    MQProducer mqProducer;

    private static final String QUEUE_KEY = "test_queue";

    @Test
    public void send()
    {
    	String message = "hello rabbitMQ!";
//        Map<String,Object> msg = new HashMap<String,Object>();
//        msg.put("data","hello,rabbmitmq!");
        mqProducer.sendDataToQueue(QUEUE_KEY,message);
    }
}

后台日志:

[org.springframework.context.support.DefaultLifecycleProcessor] - Starting beans in phase 2147483647
=========發送消息開始=============消息:hello rabbitMQ!
=============監聽【QueueListenter】消息(Body:'hello rabbitMQ!'MessageProperties [headers={}, timestamp=null, messageId=null, userId=null, appId=null, clusterId=null, type=null, correlationId=null, replyTo=null, contentType=text/plain, contentEncoding=UTF-8, contentLength=0, deliveryMode=PERSISTENT, expiration=null, priority=0, redelivered=false, receivedExchange=test-mq-exchange, receivedRoutingKey=test_queue, deliveryTag=1, messageCount=0])
=====獲取消息hello rabbitMQ![org.springframework.context.support.GenericApplicationContext] - Closing org.springframework.context.support.GenericApplicationContext@349955ab: startup date [Sun Sep 11 17:34:30 CST 2016]; root of context hierarchy

整合成功!

看日志:

(Body:'hello rabbitMQ!'MessageProperties [headers={}, timestamp=null, messageId=null, userId=null, appId=null, clusterId=null, type=null, correlationId=null, replyTo=null, contentType=text/plain, contentEncoding=UTF-8, contentLength=0, deliveryMode=PERSISTENT, expiration=null, priority=0, redelivered=false, receivedExchange=test-mq-exchange, receivedRoutingKey=test_queue, deliveryTag=1, messageCount=0])

知道消息是由Header和Body組成,Header是由生產者添加的各種屬性的集合,包括Message是否被持久化、由哪個Message Queue接受、優先級是多少等。而Body是真正需要傳輸的APP數據。

 4、rabbitMQ的客戶端配置

根據上面3.2節 spring的整合配置文件之后,還需要配置rabbitMQ 的客戶端。配置貼圖:

 

 5、后續補充內容

根據上面一章,添加新的queue之后,都需要手動配置客戶端,這樣顯得很麻煩,這里有配置,添加下面配置,客戶端我們就不用再關心,重點放在我們的代碼上面。如下配置:

<!-- queue 隊列聲明 -->
<rabbit:queue id="dealDataQueue" name="test.deal.data.queue" durable="true" auto-delete="false" exclusive="false"/>

<!-- exchange queue binging key 綁定 -->
<rabbit:direct-exchange name="xx-exchange" id="xx-exchange" durable="true" auto-delete="false">
        <rabbit:bindings>
                <rabbit:binding queue="dealDataQueue" key="test.deal.data.queue"/>
        </rabbit:bindings>
</rabbit:direct-exchange>

<!--定義 MQ 監聽器 bean-->
<bean id="dealDataQueueLitener" class="com.xxx.DealDataListener"/>

<!-- 監聽 綁定 queue -->
<rabbit:listener-container connection-factory="rabbitConnectionFactory" acknowledge="auto">
      <!--監聽器監聽該queue -->
      <rabbit:listener queues="dealDataQueue" ref="dealDataQueueLitener"/>
</rabbit:listener-container>

<!-- config exchange -->
<rabbit:template id="rabbitTemplate" exchange="xx-exchange" connection-factory="rabbitConnectionFactory" />

 以上內容都是我個人學習補充,由於能力有限,難免出現錯誤,如有錯誤,多謝指正。

 

 參考資料:

1、RabbitMQ官方網站

2、RabbitMQ的幾種典型使用場景

3、CSDN專欄

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM