项目集成篇: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,并实现了消息的发送和消费功能。如果有任何问题或需要进一步的帮助,请随时提问!

相关推荐
北风toto6 小时前
Spring Boot / Spring Cloud 配置文件加密详解:使用 jasypt-spring-boot 实现 ENC() 加密
spring boot·后端·spring cloud
代码羊羊6 小时前
Rust 格式化输出完全攻略:从入门到精通
开发语言·后端·rust
Rust研习社6 小时前
Rust + PostgreSQL 极简技术栈应用开发
开发语言·数据库·后端·http·postgresql·rust
geovindu6 小时前
go:Template Method Pattern
开发语言·后端·设计模式·golang·模板方法模式
白晨并不是很能熬夜6 小时前
【RPC】第 4 篇:服务发现 — Zookeeper + 缓存容错
java·后端·程序人生·缓存·zookeeper·rpc·服务发现
我这一拳20年的功力6 小时前
深入解析 XXL-JOB 核心原理:从 Quartz 到自研时间轮
后端
MgArcher6 小时前
一个下划线表示“别动”,两个下划线表示“真别动”!Python属性访问控制,看懂这篇就够了
后端
ltl6 小时前
【大模型基础设施工程】19:Agent 框架工程
后端
Leinwin7 小时前
Claude 四月宕机七次:从一次事故看企业级 AI 部署的容灾设计
后端·python·flask
是希燃亚7 小时前
hermes迁移手册,将hermes迁移到不同服务器~
后端·github