第 4-6 課:Spring Boot RabbitMQ 詳解

RabbitMQ 介紹

AMQP(Advanced Message Queuing Protocol,高級消息隊列協議)是應用層協議的一個開放標準,爲面向消息的中間件設計。消息中間件主要用於組件之間的解耦,消息的發送者無需知道消息使用者的存在,反之亦然。

AMQP 的主要特徵是面向消息、隊列、路由(包括點對點和發佈/訂閱)、可靠性、安全。

RabbitMQ 是一個開源的 AMQP 實現,服務器端用 Erlang 語言編寫,支持多種客戶端,如 Python、Ruby、.NET、Java、JMS、C、PHP、ActionScript、XMPP、STOMP 等,支持 AJAX。用於在分佈式系統中存儲轉發消息,在易用性、擴展性、高可用性等方面表現不俗。

相關概念

通常我們談到隊列服務,會有三個概念:發消息者、隊列、收消息者。RabbitMQ 在這個基本概念之上,多做了一層抽象,在發消息者和隊列之間加入了交換器(Exchange)。這樣發消息者和隊列就沒有直接聯繫,轉而變成發消息者把消息給交換器,交換器根據調度策略再把消息再給隊列。

  • 左側 P 代表生產者,也就是往 RabbitMQ 發消息的程序。
  • 中間即是 RabbitMQ,其中包括了交換機和隊列。
  • 右側 C 代表消費者,也就是往 RabbitMQ 拿消息的程序。

那麼,其中比較重要的概念有 4 個,分別爲:虛擬主機、交換機、隊列和綁定。

  • 虛擬主機:一個虛擬主機持有一組交換機、隊列和綁定,爲什麼需要多個虛擬主機呢?很簡單,RabbitMQ 當中,用戶只能在虛擬主機的粒度進行權限控制。因此,如果需要禁止 A 組訪問 B 組的交換機/隊列/綁定,必須爲 A 和 B 分別創建一個虛擬主機,每一個 RabbitMQ 服務器都有一個默認的虛擬主機“/”。
  • 交換機:Exchange 用於轉發消息,但是它不會做存儲,如果沒有 Queue bind 到 Exchange 的話,它會直接丟棄掉 Producer 發送過來的消息。

這裏有一個比較重要的概念:路由鍵 。消息到交換機的時候,交互機會轉發到對應的隊列中,那麼究竟轉發到哪個隊列,就要根據該路由鍵。

  • 綁定:也就是交換機需要和隊列相綁定,這其中如上圖所示,是多對多的關係。

交換機(Exchange)

交換機的功能主要是接收消息並且轉發到綁定的隊列,交換機不存儲消息,在啓用 ack 模式後,交換機找不到隊列,會返回錯誤。交換機有四種類型:Direct、topic、Headers and Fanout。

  • Direct:其類型的行爲是“先匹配、再投送”,即在綁定時設定一個 routing_key,消息的 routing_key 匹配時,纔會被交換器投送到綁定的隊列中去。
  • Topic:按規則轉發消息(最靈活)。
  • Headers:設置 header attribute 參數類型的交換機。
  • Fanout:轉發消息到所有綁定隊列。

Direct Exchange

Direct Exchange 是 RabbitMQ 默認的交換機模式,也是最簡單的模式,根據 key 全文匹配去尋找隊列。

第一個 X - Q1 就有一個 binding key,名字爲 orange;X - Q2 就有 2 個 binding key,名字爲 black 和 green。當消息中的路由鍵和這個 binding key 對應上的時候,那麼就知道了該消息去到哪一個隊列中。

注意:爲什麼 X 到 Q2 要有 black、green,2 個 binding key 呢,一個不就行了嗎?這個主要是因爲可能又有 Q3,而 Q3 只接收 black 的信息,而 Q2 不僅接收 black 的信息,還接收 green 的信息。

Topic Exchange

Topic Exchange 轉發消息主要是根據通配符。在這種交換機下,隊列和交換機的綁定會定義一種路由模式,那麼,通配符就要在這種路由模式和路由鍵之間匹配後交換機才能轉發消息。

在這種交換機模式下:

  • 路由鍵必須是一串字符,用句號(.)隔開,比如 agreements.us,或者 agreements.eu.stockholm 等;
  • 路由模式必須包含一個 星號(* ),主要用於匹配路由鍵指定位置的一個單詞,比如,一個路由模式是這樣子,agreements..b.*,那麼就只能匹配路由鍵是這樣子的,第一個單詞是 agreements,第四個單詞是 b;井號(#)就表示相當於一個或者多個單詞,例如一個匹配模式是 agreements.eu.berlin.#,那麼,以 agreements.eu.berlin 開頭的路由鍵都是可以的。

具體代碼發送的時候還是一樣,第一個參數表示交換機,第二個參數表示 routing key,第三個參數即消息。如下:

rabbitTemplate.convertAndSend("testTopicExchange","key1.a.c.key2", " this is  RabbitMQ!");

Topic 和 Direct 類似, 只是匹配上支持了“模式”,在“點分”的 routing_key 形式中, 可以使用兩個通配符:

  • * 表示一個詞
  • # 表示零個或多個詞

Headers Exchange

Headers 也是根據規則匹配,相較於 Direct 和 Topic 固定地使用 routing_key,headers 則是一個自定義匹配規則的類型。

在隊列與交換器綁定時,會設定一組鍵值對規則,消息中也包括一組鍵值對(headers 屬性),當這些鍵值對有一對或全部匹配時,消息被投送到對應隊列。

Fanout Exchange

Fanout Exchange 消息廣播的模式,不管路由鍵或者是路由模式,會把消息發給綁定給它的全部隊列,如果配置了 routing_key 會被忽略。

Spring Boot 集成 RabbitMQ

Spring Boot 集成 RabbitMQ 非常簡單,僅需非常少的配置就可使用,Spring Boot 提供了 spring-boot-starter-amqp 組件對 MQ 消息支持。

簡單使用

(1)配置 pom 包,主要是添加 spring-boot-starter-amqp 的支持

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

(2)配置文件

配置 rabbitmq 的安裝地址、端口以及賬戶信息:

spring.application.name=Spring-boot-rabbitmq

spring.rabbitmq.host=192.168.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.username=admin
spring.rabbitmq.password=123456

(3)定義隊列

@Configuration
public class RabbitConfig {

    @Bean
    public Queue Queue() {
        return new Queue("hello");
    }

}

(4)發送者

AmqpTemplate 是 Spring Boot 提供的默認實現:

public class HelloSender {

    @Autowired
    private AmqpTemplate rabbitTemplate;

    public void send() {
        String context = "hello " + new Date();
        System.out.println("Sender : " + context);
        this.rabbitTemplate.convertAndSend("hello", context);
    }

}

(5)接收者

注意使用註解 @RabbitListener,使用 queues 指明隊列名稱,@RabbitHandler 爲具體接收的方法。

@Component
@RabbitListener(queues = "hello")
public class HelloReceiver {

    @RabbitHandler
    public void process(String hello) {
        System.out.println("Receiver  : " + hello);
    }

}

(6)測試

@RunWith(SpringRunner.class)
@Spring BootTest
public class RabbitMqHelloTest {

    @Autowired
    private HelloSender helloSender;

    @Test
    public void hello() throws Exception {
        helloSender.send();
        Thread.sleep(1000l);
    }

}

注意,發送者和接收者的 queue name 必須一致,不然不能接收。

讓測試方法等待一秒,讓接收者接收到消息,不然應用退出時可能還沒有接收到消息。

以上一個最常用簡單的示例就完成了,下面我們介紹更復雜的使用場景。

多方測試

一個發送者和 N 個接收者或者 N 個發送者和 N 個接收者會出現什麼情況呢?

一對多發送

對上面的代碼進行了小改造,接收端註冊了兩個 Receiver,Receiver1 和 Receiver2,發送端加入參數計數,接收端打印接收到的參數,下面是測試代碼,發送一百條消息,來觀察兩個接收端的執行效果。

發送者示例:

@Component
public class NeoSender {

    @Autowired
    private AmqpTemplate rabbitTemplate;

    public void send(int i) {
        String context = "Spring boot neo queue"+" ****** "+i;
        System.out.println("Sender1 : " + context);
        this.rabbitTemplate.convertAndSend("neo", context);
    }

}

接收者 1 示例,接收者 2 和 1基本一致。

@Component
@RabbitListener(queues = "neo")
public class NeoReceiver1 {

    @RabbitHandler
    public void process(String neo) {
        System.out.println("Receiver 1: " + neo);
    }

}

我們設計了一個發送者,兩個接收者,發送一百個消息看看效果。

@Test
public void oneToMany() throws Exception {
    for (int i=0;i<100;i++){
        neoSender.send(i);
    }
    Thread.sleep(10000l);
}

結果如下:

Receiver 2: Spring boot neo queue ****** 1
Receiver 1: Spring boot neo queue ****** 0
Receiver 1: Spring boot neo queue ****** 2
Receiver 2: Spring boot neo queue ****** 3
Receiver 1: Spring boot neo queue ****** 4
Receiver 2: Spring boot neo queue ****** 5
Receiver 2: Spring boot neo queue ****** 7
Receiver 1: Spring boot neo queue ****** 6
Receiver 2: Spring boot neo queue ****** 8
Receiver 1: Spring boot neo queue ****** 9
Receiver 1: Spring boot neo queue ****** 11
Receiver 2: Spring boot neo queue ****** 10
...

根據返回結果得到以下結論:

一個發送者,N 個接收者,經過測試接收端均勻接收到消息,也說明接收端自動進行了均衡負載,我們也可以利用這個特性做流量分發。

多對多發送

複用以上的發送者和接收者,再增加一個發送者 2 加入標記,在一百個循環中相互交替發送。

發送者方法如下:

public void send(int i) {
    String context = "Spring boot neo queue"+" ****** "+i;
    System.out.println("Sender2 : " + context);
    this.rabbitTemplate.convertAndSend("neo", context);
}

兩個發送者兩個接收者的測試用例如下:

@Test
public void manyToMany() throws Exception {
    for (int i=0;i<100;i++){
        neoSender.send(i);
        neoSender2.send(i);
    }
    Thread.sleep(10000l);
}

結果如下:

Sender1 : Spring boot neo queue ****** 0
Sender2 : Spring boot neo queue ****** 0
Sender1 : Spring boot neo queue ****** 1
Sender2 : Spring boot neo queue ****** 1
Sender1 : Spring boot neo queue ****** 2
Sender2 : Spring boot neo queue ****** 2
Sender1 : Spring boot neo queue ****** 3
Sender2 : Spring boot neo queue ****** 3
Sender1 : Spring boot neo queue ****** 4
Sender2 : Spring boot neo queue ****** 4
Sender1 : Spring boot neo queue ****** 5
Sender2 : Spring boot neo queue ****** 5
...

Receiver 2: Spring boot neo queue ****** 0
Receiver 1: Spring boot neo queue ****** 0
Receiver 2: Spring boot neo queue ****** 1
Receiver 1: Spring boot neo queue ****** 1
Receiver 2: Spring boot neo queue ****** 2
Receiver 1: Spring boot neo queue ****** 2
Receiver 2: Spring boot neo queue ****** 3
Receiver 1: Spring boot neo queue ****** 3
Receiver 2: Spring boot neo queue ****** 4
Receiver 1: Spring boot neo queue ****** 4
Receiver 2: Spring boot neo queue ****** 5
Receiver 1: Spring boot neo queue ****** 5
...

結論:發送端交替發送消息,接收端仍然會均勻接收到消息。

高級使用

對象的支持

Spring Boot 已經完美的支持對象的發送和接收,不需要格外的配置。

//發送者
public void send(User user) {
    System.out.println("Sender object: " + user.toString());
    this.rabbitTemplate.convertAndSend("object", user);
}

...

//接收者
@RabbitHandler
public void process(User user) {
    System.out.println("Receiver object : " + user);
}

測試用例如下:

@Test
public void sendOject() throws Exception {
    User user=new User();
    user.setName("neo");
    user.setPass("123456");
    sender.send(user);
    Thread.sleep(1000l);
}

結果如下:

Sender object: com.neo.model.User@66971f6b[name=neo,pass=123456]
Receiver object : com.neo.model.User@14e38d67[name=neo,pass=123456]

Topic Exchange

Topic 是 RabbitMQ 中最靈活的一種方式,可以根據 routing_key 自由的綁定不同的隊列。

首先對 Topic 規則配置,這裏使用兩個隊列來測試:

@Configuration
public class TopicRabbitConfig {

    final static String message = "topic.message";
    final static String messages = "topic.messages";

    //定義隊列
    @Bean
    public Queue queueMessage() {
        return new Queue(TopicRabbitConfig.message);
    }

    @Bean
    public Queue queueMessages() {
        return new Queue(TopicRabbitConfig.messages);
    }

    //交換機
    @Bean
    TopicExchange exchange() {
        return new TopicExchange("exchange");
    }

    //將隊列和交換機綁定
    @Bean
    Binding bindingExchangeMessage(Queue queueMessage, TopicExchange exchange) {
        return BindingBuilder.bind(queueMessage).to(exchange).with("topic.message");
    }

    @Bean
    Binding bindingExchangeMessages(Queue queueMessages, TopicExchange exchange) {
        return BindingBuilder.bind(queueMessages).to(exchange).with("topic.#");
    }
}

設計 queueMessages 同時匹配兩個隊列,queueMessage 只匹配“topic.message”隊列。

發送者代碼如下:

public void send1() {
    String context = "hi, i am message 1";
    System.out.println("Sender : " + context);
    this.rabbitTemplate.convertAndSend("exchange", "topic.message", context);
}

public void send2() {
    String context = "hi, i am messages 2";
    System.out.println("Sender : " + context);
    this.rabbitTemplate.convertAndSend("exchange", "topic.messages", context);
}

接收者1代碼如下:

@Component
@RabbitListener(queues = "topic.message")
public class TopicReceiver {

    @RabbitHandler
    public void process(String message) {
        System.out.println("Topic Receiver1  : " + message);
    }

}

接收者 2 和 1 類似。

發送 send1 會匹配到 topic.# 和 topic.message 兩個 Receiver 都可以收到消息;發送 send2 只有 topic.# 可以匹配,Receiver2 監聽到了消息。

首先測試發送 send1():

@Test
public void topic1() throws Exception {
    sender.send1();
    Thread.sleep(1000l);
}

返回結果如下:

Sender : hi, i am message 1
Topic Receiver1  : hi, i am message 1
Topic Receiver2  : hi, i am message 1

說明兩個接收者都接收到了消息。

再測試發送send2():

@Test
public void topic2() throws Exception {
    sender.send2();
    Thread.sleep(1000l);
}

返回結果如下:

Sender : hi, i am messages 2
Topic Receiver2  : hi, i am messages 2

只有接收者2接收到了消息。兩個方法都滿足我們的預期,驗證了我們的設想。

Fanout Exchange

Fanout 就是我們熟悉的廣播模式或者訂閱模式,給 Fanout 交換機發送消息,綁定了這個交換機的所有隊列都收到這個消息。

Fanout 相關配置:

@Configuration
public class FanoutRabbitConfig {

    //定義隊列
    @Bean
    public Queue AMessage() {
        return new Queue("fanout.A");
    }

    @Bean
    public Queue BMessage() {
        return new Queue("fanout.B");
    }

    @Bean
    public Queue CMessage() {
        return new Queue("fanout.C");
    }

    //定義交換機
    @Bean
    FanoutExchange fanoutExchange() {
        return new FanoutExchange("fanoutExchange");
    }

    //分部進行綁定
    @Bean
    Binding bindingExchangeA(Queue AMessage,FanoutExchange fanoutExchange) {
        return BindingBuilder.bind(AMessage).to(fanoutExchange);
    }

    @Bean
    Binding bindingExchangeB(Queue BMessage, FanoutExchange fanoutExchange) {
        return BindingBuilder.bind(BMessage).to(fanoutExchange);
    }

    @Bean
    Binding bindingExchangeC(Queue CMessage, FanoutExchange fanoutExchange) {
        return BindingBuilder.bind(CMessage).to(fanoutExchange);
    }

}

這裏使用了 A、B、C 三個隊列綁定到 Fanout 交換機上面,發送端的 routing_key 寫任何字符都會被忽略:

發生者如下:

public void send() {
    String context = "hi, fanout msg ";
    System.out.println("Sender : " + context);
    this.rabbitTemplate.convertAndSend("fanoutExchange","", context);
}

接收者 A 代碼如下:

@Component
@RabbitListener(queues = "fanout.A")
public class FanoutReceiverA {

    @RabbitHandler
    public void process(String message) {
        System.out.println("fanout Receiver A: " + message);
    }

}

接收者 B、C 和接收者 A 類似,相見示例代碼。

寫測試用例調用 send() 進行測試:

@Test
public void fanoutSender() throws Exception {
    sender.send();
    Thread.sleep(1000l);
}

結果如下:

Sender : hi, fanout msg 
fanout Receiver B: hi, fanout msg 
fanout Receiver C: hi, fanout msg 
fanout Receiver A: hi, fanout msg 

結果說明,綁定到 fanout 交換機上面的隊列都收到了消息。

總結

RabbitMQ 一個非常高效的消息隊列組件,使用 RabbitMQ 可以方便的解耦項目之間的依賴,同時利用 RabbitMQ 的特性可以做很多的解決方案。Spring Boot 爲 RabbitMQ 提供了支持組件 spring-boot-starter-amqp,加載的時候會自動進行配置,並且預置了 RabbitTemplate,可以讓我們在項目中方便的調用。在測試使用的過程中發現,RabbitMQ 非常的靈活,可以使用各種策略將不同的發送者和接收者綁定在一起,這些特性在實際項目使用中非常的高效便利。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章