项目集成篇:springboot集成rabbitmq实现消息发送,消费

在Spring Boot中集成RabbitMQ以实现消息的发送和消费,可以通过使用`spring-boot-starter-amqp`来简化配置。以下是一个完整的示例,展示了如何设置一个基于Spring Boot的应用程序来与RabbitMQ进行交互。

1. 添加依赖

首先,在你的`pom.xml`文件中添加必要的依赖:

```xml

<dependencies>

<!-- Spring Boot Starter Web -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

<!-- Spring Boot Starter AMQP for RabbitMQ -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-amqp</artifactId>

</dependency>

<!-- Lombok (Optional) for reducing boilerplate code -->

<dependency>

<groupId>org.projectlombok</groupId>

<artifactId>lombok</artifactId>

<optional>true</optional>

</dependency>

<!-- Test dependencies -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-test</artifactId>

<scope>test</scope>

</dependency>

</dependencies>

```

2. 配置RabbitMQ连接

编辑`application.properties`或`application.yml`文件以包含RabbitMQ的连接信息。

`application.properties`

```properties

RabbitMQ server configuration

spring.rabbitmq.host=localhost

spring.rabbitmq.port=5672

spring.rabbitmq.username=guest

spring.rabbitmq.password=guest

```

或者使用`application.yml`

```yaml

spring:

rabbitmq:

host: localhost

port: 5672

username: guest

password: guest

```

3. 创建消息队列和交换器配置

创建一个配置类来定义RabbitMQ的队列、交换器以及绑定关系。

```java

package com.example.config;

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;

@Configuration

public class RabbitMQConfig {

public static final String QUEUE_NAME = "example_queue";

public static final String EXCHANGE_NAME = "example_exchange";

public static final String ROUTING_KEY = "example_routing_key";

@Bean

public Queue queue() {

return new Queue(QUEUE_NAME, false);

}

@Bean

public TopicExchange exchange() {

return new TopicExchange(EXCHANGE_NAME);

}

@Bean

public Binding binding(Queue queue, TopicExchange exchange) {

return BindingBuilder.bind(queue).to(exchange).with(ROUTING_KEY);

}

}

```

4. 创建消息生产者

创建一个服务类来发送消息到RabbitMQ。

```java

package com.example.service;

import com.rabbitmq.client.Channel;

import lombok.extern.slf4j.Slf4j;

import org.springframework.amqp.rabbit.core.RabbitTemplate;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

@Service

@Slf4j

public class MessageProducer {

private final RabbitTemplate rabbitTemplate;

@Autowired

public MessageProducer(RabbitTemplate rabbitTemplate) {

this.rabbitTemplate = rabbitTemplate;

}

public void sendMessage(String message) {

log.info("Sending message: {}", message);

rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME, RabbitMQConfig.ROUTING_KEY, message);

}

}

```

5. 创建消息消费者

创建一个监听器类来接收并处理来自RabbitMQ的消息。

```java

package com.example.listener;

import com.rabbitmq.client.Channel;

import lombok.extern.slf4j.Slf4j;

import org.springframework.amqp.core.Message;

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

import org.springframework.stereotype.Component;

@Component

@Slf4j

public class MessageListener {

@RabbitListener(queues = RabbitMQConfig.QUEUE_NAME)

public void receiveMessage(Message message, Channel channel) throws Exception {

try {

String msg = new String(message.getBody());

log.info("Received message: {}", msg);

// 手动确认消息

channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);

} catch (Exception e) {

log.error("Failed to process message", e);

// 拒绝消息,可以选择重新入队或者丢弃

channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);

}

}

}

```

6. 创建控制器(可选)

你可以创建一个REST控制器来触发消息的发送。

```java

package com.example.controller;

import com.example.service.MessageProducer;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

@RestController

@RequestMapping("/api/message")

@Slf4j

public class MessageController {

@Autowired

private MessageProducer producer;

@PostMapping("/send")

public String sendMessage(@RequestParam String message) {

producer.sendMessage(message);

return "Message sent!";

}

}

```

注意事项

  • 确保你的RabbitMQ服务器正在运行并且可以从应用程序访问。

  • 如果你在本地开发,请确保RabbitMQ服务已正确安装并在默认端口5672上运行。

  • 根据实际情况调整包名、路径以及其他细节。

  • 对于生产环境,建议配置RabbitMQ的用户名和密码认证,并考虑更复杂的错误处理机制和日志记录。

通过上述步骤,你已经成功地在一个Spring Boot应用中集成了RabbitMQ,并实现了消息的发送和消费功能。如果有任何问题或需要进一步的帮助,请随时提问!

相关推荐
SimonKing32 分钟前
MyBatis的隐形炸弹:selectByExampleWithBLOBs使用不当,让性能下降80%
java·后端·程序员
踏浪无痕36 分钟前
告别 Grafana 手搓 Dashboard:基于指标分组的 Prometheus 可视化新方案
后端·架构·产品
天天摸鱼的java工程师37 分钟前
分布式 ID 生成终极方案:雪花算法优化与高可用实现
java·后端
掘金者阿豪39 分钟前
Jenkins 任务中的 `java.lang.InterruptedException` 异常解析与解决
后端
superman超哥42 分钟前
Rust 零拷贝技术应用:极致性能的内存操作艺术
开发语言·后端·rust·rust零拷贝技术·内存操作
间彧42 分钟前
深度解析AIOps:从架构设计到工具实践的智能运维体系
后端
superman超哥43 分钟前
Rust SIMD 指令优化:数据并行的极致性能
开发语言·后端·rust·数据并行·指令优化
嘻哈baby1 小时前
慢SQL排查与优化实战:从定位到根治
后端
倚栏听风雨1 小时前
我们对一个文本向量化存储后 ,如果这个文本发生了变化 ,如何更新向量库里的数据
后端
倚栏听风雨1 小时前
向量数据库 Milvus 简介
后端