一文带你彻底搞懂SpringBoot-RabbitMQ(1)

本文详细介绍了如何使用SpringBoot整合RabbitMQ,包括环境搭建、四大交换器(Direct、Topic、Fanout、Headers)的使用,以及发送者异常监控和消息持久化的实现。通过实例展示了各种交换器的消息发送和接收过程,同时探讨了异常情况下的补偿机制。
摘要由CSDN通过智能技术生成

一、环境搭建

  1. 采用maven多module模式,共计创建三个子module
    • common:通用实体信息
    • rabbitmq-publisher:消息发布者,基于SpringBoot
    • rabbitmq-subscriber:消息订阅者,基于SpringBoot
  2. 在消息发布者和订阅者两个项目中加入rabbitmq maven依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
复制代码

在两个项目中加入rabbitmq的配置信息

spring:
  rabbitmq:
    host: xxx.xxx.xxx.xxx
    port: 5672
    username: username
    password: password
    # 虚拟主机,需要后台先配置
    # virtual-host: springboot
复制代码

上述三步完成后,rabbitmq的基础环境搭建完成

rabbitmq配置属性类

  • org.springframework.boot.autoconfigure.amqp.RabbitProperties

二、四大交换器

2.1 direct - 直连交换器

2.1.1 消息发送者

在消息发布者中新建配置类,声明交换器信息

  • 只用声明交换器,队列和交换器绑定是订阅者操作
  • 不同的类型提供不同的交换器
  • 如果只声明交换器并不会创建交换器,而是绑定时或者发送消息时才创建
import org.springframework.amqp.core.DirectExchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AmqpPublisherConfig {
    @Bean
    public DirectExchange emailDirectExchange() {
        // 声明方式一
        // return new DirectExchange("exchange.direct.springboot.email");
        // 声明方式二
        return ExchangeBuilder.directExchange("exchange.direct.springboot.email").build();
    }
}
复制代码

发送消息时,使用的是RabbitTemplate,为SpringBoot提供的RabbitMQ消息发送器

  • org.springframework.amqp.rabbit.core.RabbitTemplate
  • 发送消息示例
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;

@RestController
public class PublishController {
    @Resource
    private RabbitTemplate rabbitTemplate;

    @RequestMapping("/direct")
    public Object direct(String message) {
        try {
            rabbitTemplate.convertAndSend("交换器", "路由键", message);
            return message;
        } catch (AmqpException e) {
            System.out.println(e.getMessage());
            return "网络中断,请稍后再试~";
        }
    }
}
复制代码

2.2.2 消息接收者

接收者需要配置以下内容

  • 交换器:直接new对应的交换器类型
  • 队列:只有Queue类型,通过名称区分
  • 交换器和队列的绑定:通过BindingBuilder.bind(队列).to(交换器).with(路由键);
  • 只声明交换器和队列绑定,并不会马上创建,而是在发送消息或者监听队列时才会创建
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AmqpSubscriberConfig {
   /**
     * 直连交换器
     */
    @Bean
    public DirectExchange emailDirectExchange() {
        // 声明方式一
        // return new DirectExchange("exchange.direct.springboot.email");
        // 声明方式二
        return ExchangeBuilder.directExchange("exchange.direct.springboot.email").build();
    }

    /**
     * 声明队列
     */
    @Bean
    public Queue emailQueue() {
        // 声明方式一
        // return new Queue("queue.direct.springboot.email");
        // 声明方式二
        return QueueBuilder.durable("queue.direct.springboot.email").build();
    }

    /**
     * 交换器和队列绑定
     */
    @Bean
    @Resource
    public Binding emailBiding(Queue emailQueue, DirectExchange emailDirectExchange) {
        // 将路由使用路由键绑定到交换器上
        return BindingBuilder.bind(emailQueue).to(emailDirectExchange).with("springboot.email.routing.key");
    }
}
复制代码

监听队列

  • 监听的队列必须存在,否则将会报错
  • 监听的队列消费完成会自动确认消息
  • 如果多个队列同时监听一个队列,则消息会轮训地由不同方法处理
  • 可以在参数中指定接收类型,消息将会自动转为对应类型
  • 也可以指定Message参数获取对应消息信息
    • org.springframework.amqp.core.Message
    • 获取消息属性:message.getMessageProperties()
    • 获取消息内容:message.getBody()
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * 消息订阅监听
 */
@Component
public class SubscriberListener {
    /**
     * direct监听,相同监听队列消息将会轮流处理
     */
    @RabbitListener(queues = "queue.direct.springboot.email")
    public void receiver01(String msg) {
        System.out.println("receiver01 message = " + msg);
    }

    @RabbitListener(queues = "queue.direct.springboot.email")
    public void receiver02(String msg) {
        System.out.println("receiver02  message = " + msg);
    }
}
复制代码

2.1.3 消息发布订阅

1.先启动订阅者,可以看到队列声明

2. 启动发布者,然后发布消息

import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;

@RestController
public class PublishController {
    @Resource
    private RabbitTemplate rabbitTemplate;

    @RequestMapping("/direct")
    public Object direct(String message) {
        try {
            // 指定发送的交换器和路由键
            rabbitTemplate.convertAndSend("exchange.direct.springboot.email", "springboot.email.routing.key", message);
            return message;
        } catch (AmqpException e) {
            System.out.println(e.getMessage());
            return "网络中断,请稍后再试~";
        }
    }
}
复制代码

3.订阅者会轮流收到信息

receiver01 message = direct
receiver02  message = direct
receiver01 message = direct
receiver02  message = direct
receiver01 message = direct
receiver02  message = direct
复制代码

2.2 topic - 主题交换器

2.2.1 消息发送者

声明topic交换器

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

@Configuration
public class BlogPublisherConfig {
    @Bean
    public Exchange blogTopicExchange() {
        return ExchangeBuilder.topicExchange("exchange.topic.springboot.blog").build();
    }
}
复制代码

声明controller

@RequestMapping("/topic")
public Object topic(String routingKey, String message) {
    rabbitTemplate.convertAndSend("exchange.topic.springboot.blog", routingKey, message);
    return routingKey + " : " + message;
}
复制代码

2.2.2 消息接收者

声明交换器、三个队列、队列的绑定

  • *:匹配一个串
  • #:匹配一个或者多个串
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Configuration
public class BlogSubscriberConfig {
    /**
     * 主题交换器
     */
    @Bean
    public TopicExchange blogTopicExchange() {
        return ExchangeBuilder.topicExchange("exchange.topic.springboot.blog").build();
    }

    @Bean
    public Queue blogJavaQueue() {
        return QueueBuilder.durable("queue.topic.springboot.blog.java").build();
    }

    @Bean
    public Queue blogMqQueue() {
        return QueueBuilder.durable("queue.topic.springboot.blog.mq").build();
    }

    @Bean
    public Queue blogAllQueue() {
        
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值