spring-boot集成rabbitmq
时间: 2025-03-27 18:21:21 浏览: 29
### Spring Boot 整合 RabbitMQ 实现消息队列
#### 添加依赖项
为了使Spring Boot项目能够与RabbitMQ交互,需在`pom.xml`文件中加入特定的依赖项。这可以通过引入`spring-boot-starter-amqp`来完成[^2]。
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
```
#### 配置RabbitMQ连接属性
接着要配置RabbitMQ的相关参数以便于建立连接。这些设置通常位于应用的配置文件内,比如`application.properties`或`application.yml`。以下是基于YAML格式的一个例子:
```yaml
spring:
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
```
#### 创建配置类
定义一个Java配置类用来声明必要的组件如队列、交换器以及绑定关系等。下面展示了一个简单的案例,其中包含了创建名为`orderQueue`的队列并与主题型交换器相联接的过程[^4]。
```java
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
@Component
public class RabbitMqConfiguration {
private static final String ORDER_QUEUE_NAME = "order.queue";
private static final String TOPIC_EXCHANGE_NAME = "topic.exchange";
@Bean
public Queue orderQueue() {
return new Queue(ORDER_QUEUE_NAME, true);
}
@Bean
public TopicExchange topicExchange() {
return new TopicExchange(TOPIC_EXCHANGE_NAME);
}
@Bean
public Binding orderBinding(Queue orderQueue, TopicExchange topicExchange) {
return BindingBuilder.bind(orderQueue).to(topicExchange).with("order.routing.key");
}
}
```
#### 编写生产者逻辑
接下来编写负责向指定路由键发送消息的服务端代码。这里给出了一段基本的例子,展示了怎样通过模板对象将一条字符串形式的消息推送到之前设定好的队列里去。
```java
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class MessageProducerService {
private final RabbitTemplate rabbitTemplate;
@Autowired
public MessageProducerService(RabbitTemplate rabbitTemplate) {
this.rabbitTemplate = rabbitTemplate;
}
public void sendMessage(String messageContent){
System.out.println("[x] Sending message : '" + messageContent + "'");
rabbitTemplate.convertAndSend("topic.exchange", "order.routing.key", messageContent);
}
}
```
#### 构建消费者部分
最后一步就是设立接收并处理来自目标队列的数据的方法。此过程涉及监听某个具体的队列,并对接收到的内容作出响应动作。
```java
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.stereotype.Component;
@Component
public class OrderConsumer implements ChannelAwareMessageListener {
@Override
public void onMessage(Message message, Channel channel) throws Exception {
byte[] body = message.getBody();
try{
System.out.println(new String(body));
// 手动确认消费成功
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
}catch (Exception e){
// 处理失败情况下的回滚操作或其他措施
channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
}
}
}
```
阅读全文
相关推荐




















