Spring Boot整合RabbitMQ

一、简介

在Spring项目中,可以使用Spring-Rabbit去操作RabbitMQ

尤其是在spring boot项目中只需要引入对应的amqp启动器依赖即可,方便的使用RabbitTemplate发送消息,使用注解接收消息。

一般在开发过程中:

生产者工程:

  1. application.yml文件配置相关信息;
  2. 在生产者工程中编写配置类,用于创建交换机和队列,并进行绑定
  3. 注入RabbitTemplate对象,通过RabbitTemplate对象发送消息到交换机

消费者工程:

  1. application.yml文件配置相关信息
  2. 创建消息处理类,用于接收队列中的消息并进行处理

二、项目结构

三、加入依赖jar

复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

四、编写配置文件

复制代码
spring:
  rabbitmq:
    username: user
    password: 123456
    virtual-host: /admin
    port: 5672
mq:
  exchange:
    name: test_exchange_topic
  queue:
    name1: test_topic_exchange_queue1
    name2: test_topic_exchange_queue2

五、编写配置类

java 复制代码
import org.springframework.amqp.core.*;
import org.springframework.amqp.core.ExchangeBuilder;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class TopicConfig {
    @Value("${mq.exchange.name}")
    private String EXCHANGENAME;
    @Value("${mq.queue.name1}")
    private String QUEUENAME1;
    @Value("${mq.queue.name2}")
    private String QUEUENAME2;
    @Bean("Exchange")
    public Exchange getExchange(){
        Exchange exchange = ExchangeBuilder.topicExchange(EXCHANGENAME).durable(false).build();
        return exchange;
    }
    @Bean("Queue1")
    public Queue getQueue1(){
        Queue build = QueueBuilder.nonDurable(QUEUENAME1).build();
        return build;
    }
    @Bean("Queue2")
    public Queue getQueue2(){
        Queue build = QueueBuilder.nonDurable(QUEUENAME2).build();
        return build;
    }
    @Bean("Binding1")
    public Binding bindingQueueToExchange1(@Qualifier("Exchange")Exchange exchange,@Qualifier("Queue1") Queue queue){
        Binding noargs = BindingBuilder.bind(queue).to(exchange).with("test.#").noargs();
        return noargs;
    }
    @Bean("Binding2")
    public Binding bindingQueueToExchange2(@Qualifier("Exchange")Exchange exchange,@Qualifier("Queue2") Queue queue){
        Binding noargs = BindingBuilder.bind(queue).to(exchange).with("test.*").noargs();
        return noargs;
    }
}

六、测试类

java 复制代码
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;

@SpringBootTest
public class ProductTest {

    @Value("${mq.exchange.name}")
    private String EXCHANGENAME;
    @Resource
    RabbitTemplate rabbitTemplate;
    @org.junit.jupiter.api.Test
    public void t1(){
        rabbitTemplate.convertAndSend(EXCHANGENAME,"test.t","随便测试");
    }
}

七. 消费者消费消息

java 复制代码
@Component
public class Comm {
    @RabbitListener(queues = "test_topic_exchange_queue1")
    public void t1(Message message){
        byte[] body = message.getBody();
        String string = new String(body);
        System.out.println(string+"----------------");
    }

}

八、消息的可靠性传递

1.Confirm

(1) 修改application.yml文件

(2) 写一个测试类

java 复制代码
@SpringBootTest
public class ProductTest {

    @Value("${mq.exchange.name}")
    private String EXCHANGENAME;
    @Resource
    RabbitTemplate rabbitTemplate;
    @org.junit.jupiter.api.Test
    public void t2(){
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean b, String s) {
                if (b) {
                    System.out.println("发送成功");
                }else {
                    System.out.println("发送不成功"+s);
                }
            }
        });
        rabbitTemplate.convertAndSend(EXCHANGENAME,"test.t","随便测试");
    }
}

2. Return

(1) 配置文件中设置回退模式

复制代码
spring:
  rabbitmq:
    username: user
    password: 123456
    virtual-host: /admin
    port: 5672
    host: 192.168.44.64
    publisher-returns: true
#    publisher-confirm-type: correlated
mq:
  exchange:
    name: test_exchange_topic
  queue:
    name1: test_topic_exchange_queue1
    name2: test_topic_exchange_queue2

(2) 测试

java 复制代码
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;

@SpringBootTest
public class ProductTest {

    @Value("${mq.exchange.name}")
    private String EXCHANGENAME;
    @Resource
    RabbitTemplate rabbitTemplate;
    @org.junit.jupiter.api.Test
    public void t1(){
        rabbitTemplate.convertAndSend(EXCHANGENAME,"test.t","随便测试");

    }
    @org.junit.jupiter.api.Test
    public void t2(){
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean b, String s) {
                if (b) {
                    System.out.println("发送成功");
                }else {
                    System.out.println("发送不成功"+s);
                }
            }
        });
        rabbitTemplate.convertAndSend(EXCHANGENAME,"test.t","随便测试");
    }
    @org.junit.jupiter.api.Test
    public void t3(){
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setReturnsCallback(returnedMessage ->
                System.out.println("消息回退"+new String(returnedMessage.getMessage().getBody())));
        rabbitTemplate.convertAndSend(EXCHANGENAME,"test.a","测试测试");
    }
}
相关推荐
忧郁的Mr.Li7 小时前
SpringBoot中实现多数据源配置
java·spring boot·后端
暮色妖娆丶8 小时前
SpringBoot 启动流程源码分析 ~ 它其实不复杂
spring boot·后端·spring
Coder_Boy_8 小时前
Deeplearning4j+ Spring Boot 电商用户复购预测案例中相关概念
java·人工智能·spring boot·后端·spring
爱学英语的程序员8 小时前
面试官:你了解过哪些数据库?
java·数据库·spring boot·sql·mysql·mybatis
Java新手村8 小时前
基于 Vue 3 + Spring Boot 3 的 AI 面试辅助系统:实时语音识别 + 大模型智能回答
vue.js·人工智能·spring boot
消失的旧时光-19439 小时前
第十四课 · 实战篇:Redis 缓存系统落地指南(Spring Boot 从 0 到可用)
spring boot·redis·缓存
wxin_VXbishe9 小时前
C#(asp.net)学员竞赛信息管理系统-计算机毕业设计源码28790
java·vue.js·spring boot·spring·django·c#·php
森焱森10 小时前
详解 Spring Boot、Flask、Nginx、Redis、MySQL 的关系与协作
spring boot·redis·python·nginx·flask
Coder_Boy_10 小时前
Deeplearning4j+ Spring Boot 电商用户复购预测案例
java·人工智能·spring boot·后端·spring