一塊兒來學SpringBoot | 第十二篇:初探RabbitMQ消息隊列

SpringBoot 是爲了簡化 Spring 應用的建立、運行、調試、部署等一系列問題而誕生的產物, 自動裝配的特性讓咱們能夠更好的關注業務自己而不是外部的XML配置,咱們只需遵循規範,引入相關的依賴就能夠輕易的搭建出一個 WEB 工程

MQ全稱(Message Queue)又名消息隊列,是一種異步通信的中間件。能夠將它理解成郵局,發送者將消息傳遞到郵局,而後由郵局幫咱們發送給具體的消息接收者(消費者),具體發送過程與時間咱們無需關心,它也不會干擾我進行其它事情。常見的MQ有kafkaactivemqzeromqrabbitmq 等等,各大MQ的對比和優劣勢能夠自行Google前端

<!-- more -->java

rabbitmq

RabbitMQ是一個遵循AMQP協議,由面向高併發的erlanng語言開發而成,用在實時的對可靠性要求比較高的消息傳遞上,支持多種語言客戶端。支持延遲隊列(這是一個很是有用的功能)....linux

基礎概念

Broker:簡單來講就是消息隊列服務器實體
Exchange:消息交換機,它指定消息按什麼規則,路由到哪一個隊列
Queue:消息隊列載體,每一個消息都會被投入到一個或多個隊列
Binding:綁定,它的做用就是把exchangequeue按照路由規則綁定起來
Routing Key:路由關鍵字,exchange根據這個關鍵字進行消息投遞
vhost:虛擬主機,一個broker裏能夠開設多個vhost,用做不一樣用戶的權限分離
producer:消息生產者,就是投遞消息的程序
consumer:消息消費者,就是接受消息的程序
channel:消息通道,在客戶端的每一個鏈接裏,可創建多個channel,每一個channel表明一個會話任務git

基於Centos7.x安裝請參考: http://blog.battcn.com/2017/08/20/linux/linux-centos7-ribbitmq/github

常見應用場景

  1. 郵箱發送:用戶註冊後投遞消息到rabbitmq中,由消息的消費方異步的發送郵件,提高系統響應速度
  2. 流量削峯:通常在秒殺活動中應用普遍,秒殺會由於流量過大,致使應用掛掉,爲了解決這個問題,通常在應用前端加入消息隊列。用於控制活動人數,將超過此必定閥值的訂單直接丟棄。緩解短期的高流量壓垮應用。
  3. 訂單超時:利用rabbitmq的延遲隊列,能夠很簡單的實現訂單超時的功能,好比用戶在下單後30分鐘未支付取消訂單
  4. 還有更多應用場景就不一一列舉了.....

導入依賴

pom.xml 中添加 spring-boot-starter-amqp的依賴web

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-amqp</artifactId>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.46</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

屬性配置

application.properties 文件中配置rabbitmq相關內容,值得注意的是這裏配置了手動ACK的開關spring

spring.rabbitmq.username=battcn
spring.rabbitmq.password=battcn
spring.rabbitmq.host=192.168.0.133
spring.rabbitmq.port=5672
spring.rabbitmq.virtual-host=/
# 手動ACK 不開啓自動ACK模式,目的是防止報錯後未正確處理消息丟失 默認 爲 none
spring.rabbitmq.listener.simple.acknowledge-mode=manual

具體編碼

定義隊列

若是手動建立過或者RabbitMQ中已經存在該隊列那麼也能夠省略下述代碼...json

package com.battcn.config;

import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * RabbitMQ配置
 *
 * @author Levin
 * @since 2018/4/11 0011
 */
@Configuration
public class RabbitConfig {

    public static final String DEFAULT_BOOK_QUEUE = "dev.book.register.default.queue";
    public static final String MANUAL_BOOK_QUEUE = "dev.book.register.manual.queue";

    @Bean
    public Queue defaultBookQueue() {
        // 第一個是 QUEUE 的名字,第二個是消息是否須要持久化處理
        return new Queue(DEFAULT_BOOK_QUEUE, true);
    }

    @Bean
    public Queue manualBookQueue() {
        // 第一個是 QUEUE 的名字,第二個是消息是否須要持久化處理
        return new Queue(MANUAL_BOOK_QUEUE, true);
    }
}

實體類

建立一個Usercentos

public class Book implements java.io.Serializable {

    private static final long serialVersionUID = -2164058270260403154L;

    private String id;
    private String name;
    // 省略get set ...
}

控制器

編寫一個Controller類,用於消息發送工做服務器

package com.battcn.controller;

import com.battcn.config.RabbitConfig;
import com.battcn.entity.Book;
import com.battcn.handler.BookHandler;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Levin
 * @since 2018/4/2 0002
 */
@RestController
@RequestMapping(value = "/books")
public class BookController {

    private final RabbitTemplate rabbitTemplate;

    @Autowired
    public BookController(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    /**
     * this.rabbitTemplate.convertAndSend(RabbitConfig.DEFAULT_BOOK_QUEUE, book); 對應 {@link BookHandler#listenerAutoAck}
     * this.rabbitTemplate.convertAndSend(RabbitConfig.MANUAL_BOOK_QUEUE, book); 對應 {@link BookHandler#listenerManualAck}
     */
    @GetMapping
    public void defaultMessage() {
        Book book = new Book();
        book.setId("1");
        book.setName("一塊兒來學Spring Boot");
        this.rabbitTemplate.convertAndSend(RabbitConfig.DEFAULT_BOOK_QUEUE, book);
        this.rabbitTemplate.convertAndSend(RabbitConfig.MANUAL_BOOK_QUEUE, book);
    }
}

消息消費者

默認狀況下 spring-boot-data-amqp 是自動ACK機制,就意味着 MQ 會在消息消費完畢後自動幫咱們去ACK,這樣依賴就存在這樣一個問題:若是報錯了,消息不會丟失,會無限循環消費,很容易就吧磁盤空間耗完,雖然能夠配置消費的次數但這種作法也有失優雅。目前比較推薦的就是咱們手動ACK而後將消費錯誤的消息轉移到其它的消息隊列中,作補償處理

package com.battcn.handler;

import com.battcn.config.RabbitConfig;
import com.battcn.entity.Book;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * BOOK_QUEUE 消費者
 *
 * @author Levin
 * @since 2018/4/11 0011
 */
@Component
public class BookHandler {

    private static final Logger log = LoggerFactory.getLogger(BookHandler.class);

    /**
     * <p>TODO 該方案是 spring-boot-data-amqp 默認的方式,不太推薦。具體推薦使用  listenerManualAck()</p>
     * 默認狀況下,若是沒有配置手動ACK, 那麼Spring Data AMQP 會在消息消費完畢後自動幫咱們去ACK
     * 存在問題:若是報錯了,消息不會丟失,可是會無限循環消費,一直報錯,若是開啓了錯誤日誌很容易就吧磁盤空間耗完
     * 解決方案:手動ACK,或者try-catch 而後在 catch 裏面講錯誤的消息轉移到其它的系列中去
     * spring.rabbitmq.listener.simple.acknowledge-mode=manual
     * <p>
     *
     * @param book 監聽的內容
     */
    @RabbitListener(queues = {RabbitConfig.DEFAULT_BOOK_QUEUE})
    public void listenerAutoAck(Book book, Message message, Channel channel) {
        // TODO 若是手動ACK,消息會被監聽消費,可是消息在隊列中依舊存在,若是 未配置 acknowledge-mode 默認是會在消費完畢後自動ACK掉
        final long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            log.info("[listenerAutoAck 監聽的消息] - [{}]", book.toString());
            // TODO 通知 MQ 消息已被成功消費,能夠ACK了
            channel.basicAck(deliveryTag, false);
        } catch (IOException e) {
            try {
                // TODO 處理失敗,從新壓入MQ
                channel.basicRecover();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    @RabbitListener(queues = {RabbitConfig.MANUAL_BOOK_QUEUE})
    public void listenerManualAck(Book book, Message message, Channel channel) {
        log.info("[listenerManualAck 監聽的消息] - [{}]", book.toString());
        try {
            // TODO 通知 MQ 消息已被成功消費,能夠ACK了
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            // TODO 若是報錯了,那麼咱們能夠進行容錯處理,好比轉移當前消息進入其它隊列
        }
    }
}

主函數

package com.battcn;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author Levin
 */
@SpringBootApplication
public class Chapter11Application {

    public static void main(String[] args) {
        SpringApplication.run(Chapter11Application.class, args);
    }
}

測試

完成準備事項後,啓動Chapter11Application 訪問 http://localhost:8080/books 將會看到以下內容,就表明一切正常....

2018-05-22 19:04:26.708  INFO 23752 --- [cTaskExecutor-1] com.battcn.handler.BookHandler           : [listenerAutoAck 監聽的消息] - [com.battcn.entity.Book@77d8be18]
2018-05-22 19:04:26.709  INFO 23752 --- [cTaskExecutor-1] com.battcn.handler.BookHandler           : [listenerManualAck 監聽的消息] - [com.battcn.entity.Book@8bb452]

總結

目前不少大佬都寫過關於 SpringBoot 的教程了,若有雷同,請多多包涵,本教程基於最新的 spring-boot-starter-parent:2.0.2.RELEASE編寫,包括新版本的特性都會一塊兒介紹...

說點什麼

  • 我的QQ:1837307557
  • battcn開源羣(適合新手):391619659
  • 微信公衆號(歡迎調戲):battcn

公衆號

我的博客:http://blog.battcn.com/

全文代碼:https://github.com/battcn/spring-boot2-learning/tree/master/chapter11

相關文章
相關標籤/搜索