Spring Boot下使用RabbitMQ

Java RabbitMQ实践
本文详细介绍在Java环境下使用RabbitMQ的三种方式:原始方式、结合Spring框架和结合SpringBoot框架,通过实例演示发布订阅模式的实现。

概述


本文主要一下在JAVA 中使用Rabbit MQ的三种方式:

  • 原始方式
  • 结合Spring
  • 结合Spring Boot

下面将使用逐步演进的方式来讲解JAVA下如何使用Rabbit MQ发布订阅模式


最原始的方式


本文的DEMO是用Window版本的Rabbit MQ的,具体的安装方式,可以参考:

我们先将Rabbit MQ Client 引入进来。

 <dependency>
        <groupId>com.rabbitmq</groupId>
        <artifactId>amqp-client</artifactId>
        <version>5.7.3</version>
 </dependency>

建立一个MsgSender类来实现消息发送。

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class MsgSender {
    private final static String EXCHANGE_NAME = "hello_fanout_1";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("127.0.0.1");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        //发布订阅者模式
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.FANOUT);

        String message = "hello world.";
        channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes());
        channel.close();
        connection.close();
    }
}

直接执行后,可以在Rabbit MQ的管理界面看到,hello_fanout_1这个exchange已经成功创建了。
在这里插入图片描述

目前hello world.这条消息已经存储在hello_fanout_1这个exchange里了,我们只需要编写一个消费者,设置一个队列且绑定上去,就可以收到消息了。

import com.rabbitmq.client.*;

import java.io.IOException;

public class MsgReceiver {
    private final static String EXCHANGE_NAME = "hello_fanout_1";
    private final static String QUEUE_NAME = "hello_queue_1";

    public static void main(String[] args) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("127.0.0.1");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "");
        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)  throws IOException {
                String message = new String(body, "UTF-8");
                System.out.println("receive message:"+message);
            }
        };

        channel.basicConsume(QUEUE_NAME, true, consumer);
    }
}

执行完MsgReceivermain方法后,控制台输出如下:

receive message:hello world.

到此一个简单的发布订阅模式就写完了。下面使用Spring集合Rabbit MQ的方式,重构一下代码。


Spring结合Rabbit MQ


生产者Rabbit配置

import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MsgProduceRabbitConfig {
    @Bean
    public ConnectionFactory connectionFactory(){
        CachingConnectionFactory factory = new CachingConnectionFactory();
        factory.setAddresses("127.0.0.1:5672");
        return factory;
    }

    @Bean
    public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory){
        RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
        rabbitAdmin.setAutoStartup(true);
        return rabbitAdmin;
    }

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        return rabbitTemplate;
    }
}

RabbitAdmin 主要用于声明队列和交换器,而RabbitTemplate用于发送消息。为了方便测试,引入Junit

 <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-test</artifactId>
          <version>5.0.8.RELEASE</version>
          <scope>test</scope>
 </dependency>
 <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.12</version>
          <scope>test</scope>
 </dependency>

编写消息发送测试类:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={MsgProduceRabbitConfig.class})
public class MsgSendTest {
    private final static String EXCHANGE_NAME = "hello_fanout_1";
    private final static String QUEUE_NAME = "hello_queue_1";

    @Autowired
    private RabbitAdmin rabbitAdmin;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Test
    public void testSend() {
        FanoutExchange fanoutExchange = new FanoutExchange(EXCHANGE_NAME, false, false);
        Queue queue = new Queue(QUEUE_NAME, false);
        rabbitAdmin.declareExchange(fanoutExchange);
        rabbitAdmin.declareQueue(queue);
        rabbitAdmin.declareBinding(BindingBuilder.bind(queue).to(fanoutExchange));

        Message message = new Message("hello world.".getBytes(), new MessageProperties());
        rabbitTemplate.send(EXCHANGE_NAME, "", message);
    }
}

消息消费者配置类。

import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MsgConsumerRabbitConfig {
    @Bean
    public ConnectionFactory connectionFactory(){
        CachingConnectionFactory factory = new CachingConnectionFactory();
        factory.setAddresses("127.0.0.1:5672");
        return factory;
    }

    @Bean
    public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory){
        RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
        rabbitAdmin.setAutoStartup(true);
        return rabbitAdmin;
    }

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        return rabbitTemplate;
    }

    @Bean
    public SimpleMessageListenerContainer messageListenerContainer(ConnectionFactory connectionFactory){
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.setQueueNames("hello_queue_1");
        container.setMessageListener(msgListener());
        return container;
    }

    @Bean
    public MsgListener msgListener() {
        return new MsgListener();
    }

消费者端需要配置一个SimpleMessageListenerContainer类以及一个消息消费者MsgListener,并将MsgListener加入到SimpleMessageListenerContainer里去。

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;

public class MsgListener implements MessageListener{
    @Override
    public void onMessage(Message message) {
        System.out.println("receive message:" + new String(message.getBody()));
    }
}

测试类如下:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={MsgConsumerRabbitConfig.class})
public class MsgConsumerTest {
    @Test
    public void testConsumer() {
    }
}

testConsumer方法空实现就行,直接执行一下,也是输出了

receive message:hello world.


Spring Boot 整合Rabbit MQ


先引入依赖:

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

使用的Spring Boot的版本是:

2.0.4.RELEASE

由于Spring Boot跑单元测试的时候,也需要一个Spring Boot Application,因此我们手动构造一个,并且加入@EnableRabbit注解,启动监听器。

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;

/**
 * 由于是基于spring boot test组件进行单元测试,需要构建一个TestApplication上下文
 */
@SpringBootApplication
@EnableRabbit
public class TestApplication {

    public static void main(String[] args){
        SpringApplicationBuilder builder = new SpringApplicationBuilder();
        builder.environment(new StandardEnvironment());
        builder.sources(TestApplication.class);
        builder.main(TestApplication.class);
        builder.run(args);
    }
}

直接编写发送消息的测试类:

import org.junit.Test;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestApplication.class)
public class SpringBootMqSendTest{
    private final static String EXCHANGE_NAME = "hello_fanout_1";
    private final static String QUEUE_NAME = "hello_queue_1";

    @Autowired
    private RabbitAdmin rabbitAdmin;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Test
    public void testSend(){
        FanoutExchange fanoutExchange = new FanoutExchange(EXCHANGE_NAME, false, false);
        Queue queue = new Queue(QUEUE_NAME, false);
        rabbitAdmin.declareExchange(fanoutExchange);
        rabbitAdmin.declareQueue(queue);
        rabbitAdmin.declareBinding(BindingBuilder.bind(queue).to(fanoutExchange));

        Message message = new Message("hello world.".getBytes(), new MessageProperties());
        rabbitTemplate.send(EXCHANGE_NAME, "", message);
    }
}

编写消息消费者:

mport org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class SpringBootMsqConsumer {
    @RabbitListener(queues = "hello_queue_1")
    public void receive(Message message) {
        System.out.println("receive message:" + new String(message.getBody()));
    }
}

编写消息测试类:

import org.junit.Test;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestApplication.class)
public class SpringBootMqConsumerTest {
    @Autowired
    private SpringBootMsqConsumer springBootMsqConsumer;

    @Test
    public void testConsumer(){
    }
}

执行testConsumer方法后,控制台也是输出:

receive message:hello world.


总结


有上面的内容可以得知,Spring 整合Rabbit MQ的方式,使用起来也不是很方便,需要蛮多配置类的,而Spring Boot整合Rabbit MQ的方式,则简洁很多,在日常工作中,推荐使用这种方式。

<think>我们已经在之前的回答中了解了RabbitMQ的核心作用和应用场景。现在用户明确询问在Spring Boot项目中使用RabbitMQ的方法。根据引用内容,我们可以总结出以下步骤: 1. 添加依赖:在pom.xml中添加Spring BootRabbitMQ starter依赖。 2. 配置连接信息:在application.properties或application.yml中配置RabbitMQ的连接信息(主机、端口、用户名、密码等)。 3. 创建消息生产者:使用AmqpTemplate或RabbitTemplate发送消息。 4. 创建消息消费者:使用@RabbitListener注解来监听队列并处理消息。 下面我们将详细展开每个步骤,并给出代码示例。 </think>### Spring Boot 项目中 RabbitMQ使用方法 在 Spring Boot 中集成 RabbitMQ 主要通过以下步骤实现,结合引用内容和实战经验整理关键流程及注意事项: --- #### 一、核心步骤详解 1. **添加依赖** 在 `pom.xml` 中添加 RabbitMQSpring Boot Starter: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency> ``` 2. **配置连接参数** 在 `application.yml` 中配置 RabbitMQ 连接(需替换实际值): ```yaml spring: rabbitmq: host: localhost # RabbitMQ服务器地址 port: 5672 # 默认端口 username: guest # 默认用户名 password: guest # 默认密码 virtual-host: / # 虚拟主机 ``` > **注**:生产环境需替换为实际服务器地址和认证信息[^4]。 3. **定义交换机与队列** 使用 `@Configuration` 声明交换机和队列绑定: ```java @Configuration public class RabbitMQConfig { // 定义直连交换机 @Bean public DirectExchange directExchange() { return new DirectExchange("directExchange"); } // 定义队列 @Bean public Queue testQueue() { return new Queue("testQueue", true); // true表示持久化 } // 绑定队列到交换机 @Bean public Binding binding(Queue testQueue, DirectExchange directExchange) { return BindingBuilder.bind(testQueue) .to(directExchange) .with("test.routingKey"); // 路由键 } } ``` 4. **消息生产者实现** 注入 `RabbitTemplate` 发送消息: ```java @RestController public class ProducerController { @Autowired private RabbitTemplate rabbitTemplate; @GetMapping("/send") public String sendMessage() { // 发送消息到交换机 rabbitTemplate.convertAndSend( "directExchange", // 交换机名称 "test.routingKey", // 路由键 "Hello RabbitMQ!" // 消息内容 ); return "消息发送成功"; } } ``` 5. **消息消费者实现** 使用 `@RabbitListener` 监听队列: ```java @Component public class Consumer { // 监听指定队列 @RabbitListener(queues = "testQueue") public void receiveMessage(String message) { System.out.println("收到消息: " + message); // 此处添加业务处理逻辑 } } ``` --- #### 二、关键特性与实战技巧 1. **消息确认机制** - **生产者确认**:通过 `publisher-confirm-type` 配置确认模式(需在配置中启用)[^1]: ```yaml spring.rabbitmq.publisher-confirm-type: correlated ``` - **消费者确认**:手动 ACK 防止消息丢失(默认自动ACK): ```java @RabbitListener(queues = "testQueue") public void handle(Message message, Channel channel) throws IOException { try { // 业务处理 channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); } catch (Exception e) { channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true); // 重试 } } ``` 2. **消息持久化** 避免服务重启导致消息丢失: ```java // 声明队列时设置持久化 new Queue("testQueue", true, false, false); // 发送消息时设置持久化 MessageProperties props = MessagePropertiesBuilder.newInstance() .setDeliveryMode(MessageDeliveryMode.PERSISTENT).build(); rabbitTemplate.convertAndSend(exchange, routingKey, message, props); ``` 3. **常见坑点规避** - **连接超时**:配置心跳检测 `spring.rabbitmq.connection-timeout=5000` - **序列化错误**:发送对象时需实现 `Serializable` 接口 - **队列未声明**:确保消费者启动前队列已存在(或配置 `auto-declare=true`)[^1] --- #### 三、完整流程示意图 ```mermaid graph LR A[生产者] -->|convertAndSend| B(交换机) B -->|路由键匹配| C[队列] C --> D[消费者监听] D --> E[业务处理] ``` > **提示**:完整项目示例可参考 [^1] 中的代码实战部分,包含详细配置和异常处理场景。 --- ### 相关问题 1. **如何保证 RabbitMQSpring Boot 中的消息可靠性?** (涉及持久化、ACK 机制、生产者确认等技术点) 2. **Spring Boot 中如何实现 RabbitMQ 的延迟队列?** (需结合死信交换机和 TTL 实现) 3. **RabbitTemplate 和 @RabbitListener 的原理是什么?** (底层 AMQP 协议交互机制解析) 4. **如何监控 Spring Boot 集成的 RabbitMQ 运行状态?** (使用 Spring Boot Actuator 或 RabbitMQ 管理插件)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值