從0開始學Spring Boot集成Rabbit MQ

概述

記錄一次學習RabbitMQ使用的實例,整個過程也是學習的過程,一起學習,一起進步。

開發環境

JDK1.8、Spring Boot 1.5.9.RELEASE、RabbitMQ 3.7.4

Windows下RabbitMQ安裝

RabbitMQ是基於Erlang語言開發的,所以我們想要安裝還得先安裝Erlang的環境。

下載地址

Erlang官網下載地址:https://www.erlang.org/downloads
RabbitMQ官網下載地址:http://www.rabbitmq.com/download.html

安裝步驟

安裝Erlang,默認選項就行,一直點下去,如下圖所示:
Erlang安裝步驟

安裝rabbitmq,如下圖所示:
安裝RabbitMQ步驟
默認一直點下去,如果有殺毒軟件提示安裝服務,請點擊允許,如下圖所示:
安裝RabbitMQ被安全軟件攔截
至此服務安裝完畢

訪問RabbitMQ管理控制檯

網址: http://localhost:15672,用戶名:guest,密碼:guest

如圖所示:
RabbitMQ控制檯
登錄成功後看到如下界面:
RabbitMQ管理臺

Spring Boot項目創建

推薦spring官方快速創建SpringBoot項目的一個在線網站

https://start.spring.io/

在線即可完成Spring Boot項目的創建。

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>1.0.0</version>
    <packaging>jar</packaging>

    <name>demo</name>
    <description>Spring Boot & Rabbit MQ集成示例</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath />
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <debug>false</debug>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Spring Boot啓動類

package com.example;

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

@SpringBootApplication
public class DemoApplication {

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

開發及配置RabbitMQ

我們採用了監聽方式來消費消息,消息類型Topic

RabbitnqConfiguration

package com.example.config;

import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitmqConfiguration {

    //對象序列化
    @Bean
    MessageConverter jackson2JsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }
}

創建一個RabbitMQ消費者

package com.example.consumer;

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.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * Rabbit消費者
 */
@Component
public class RabbitmqConsumer {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @RabbitListener(
            bindings = @QueueBinding(
                    exchange = @Exchange(value = "${my_exchange}", type = "topic", durable = "true"),
                    value = @Queue(value = "${my_queue}", durable = "true"),
                    key = "${my_routing_key}"
            )
    )
    public void consumer(String body, Channel channel, Message message) {
        try {
            //打印接收到的消息
            System.out.println("body=" + body);
            /**
             * 告訴服務器收到這條消息 已經被我消費了
             * 可以在隊列刪掉 這樣以後就不會再發了
             * 否則消息服務器以爲這條消息沒處理掉 後續還會在發
             **/
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            logger.error("error:", e);
        }
    }
}

創建一個RabbitMQ生產者

package com.example.producter;

import javax.annotation.Resource;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * 消息生產者
 */
@RestController
public class RabbitmqProducter {

    @Resource
    private RabbitTemplate rabbitTemplate;
    @Value("${my_exchange}")
    private String exchange;
    @Value("${my_routing_key}")
    private String routingKey;

    //發送MQ交易通知消息
    @RequestMapping(value = "/api/sender", method = RequestMethod.POST)
    public void sender(@RequestBody String body) {
        //發送MQ消息
        rabbitTemplate.convertAndSend(exchange, routingKey, body);
    }
}

最後配置SpringBoot文件

  rabbitmq:
      username: guest
      password: guest
      host: 127.0.0.1
      port: 5672
      #支持發佈確認
      publisher-confirms: true
      #支持發佈返回
      publisher-returns: true
      listener:
      # prefetch: 10
        simple:
      #   採用手動應答
          acknowledge-mode: manual
      #   當前監聽容器數
          concurrency: 10
      #   最大數
          max-concurrency: 20
      #   是否支持重試
          retry:
            enabled: true

my_exchange: abcdefg
my_queue: q123456
my_routing_key: k888888

小結

@RabbitListener是整個過程的核心
RabbitTemplate是我們的核心對象

希望能給剛接觸RabbitMQ的小夥伴一點幫助~

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