SpringBoot集成 RabbitMQ 实现最简单的HelloWorld

本文介绍如何在Spring Boot项目中使用RabbitMQ消息队列进行消息传递,包括项目搭建、配置、队列创建、消息发送与接收的完整流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们以前发送消息是直接由发送方(Provider)直接发向接收方(Consumer),当使用队列了之后,就有发送方发给队列(Queue),然后有队列转发给接收方(Consumer)。队列就作为消息的中转站,起到存储消息,以及转发的功能。

对应 RabbitMQ 就不做多的说明了。下面直接开始搭建项目,看看 RabbitMQ 的实现的例子。

工程结构

项目搭建

pom.xml 文件修改

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

配置文件修改

application.properties

spring.application.name=springboot-amqp
server.port=8080

spring.rabbitmq.host=192.168.1.101
spring.rabbitmq.port=5672
spring.rabbitmq.username=admin
spring.rabbitmq.password=123456

## 这里是我在 docker 启动的时候,设置了一个 virtual host,可以根据自己的实际情况来设置
spring.rabbitmq.virtual-host=my_vhost

创建队列,用于转发发送方的消息

SenderConfig.java

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

@Configuration
public class SenderConfig {

    @Bean
    public Queue queue(){
        // 这里创建一个 名字为 hello-world-queue 的队列
        return new Queue("hello-world-queue");
    }
}

创建发送者,用于向队列中发送消息

Sender.java

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;

@Component
public class Sender {

    @Autowired
    private AmqpTemplate rabbitTemplate;

    // 通过 AmqpTemplate 向队列中发送消息
    public void send(){
        String msg = "sender " + LocalDate.now();
        // 向指定队列中发送消息
        this.rabbitTemplate.convertAndSend("hello-world-queue", msg);
    }
}

创建接收者,用于接收指定对列中的消息

Receiver.java

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class Receiver {

    // 使用 RabbitListener 来监听指定队列中的消息
    @RabbitListener(queues = {"hello-world-queue"})
    public void process(String msg){
        System.out.println("Receiver" + msg);
    }
}

测试类

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

@RunWith(SpringRunner.class)
@SpringBootTest(classes = BootRabbitmqApplication.class)
public class BootRabbitmqApplicationTests {

    @Autowired
    private Sender sender;

    @Test
    public void contextLoads() {
        this.sender.send();
    }

}

启动测试类,在控制台,就可以看到发送的消息了

我们进入管理界面,可以看到我们刚刚创建完的队列

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wayfreem

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值