rabbitmq整合springboot实战
时间: 2023-09-03 19:14:43 浏览: 137
rabbit和spring整合实战
5星 · 资源好评率100%
在Spring Boot中整合RabbitMQ可以使用Spring AMQP库来简化操作。下面是一个简单的RabbitMQ和Spring Boot的实战示例:
1. 添加依赖:在`pom.xml`文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
```
2. 配置RabbitMQ连接信息:在`application.properties`文件中添加RabbitMQ的连接信息,例如:
```properties
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
```
3. 创建消息发送者和接收者:
```java
// 消息发送者
@Component
public class MessageSender {
private final RabbitTemplate rabbitTemplate;
public MessageSender(RabbitTemplate rabbitTemplate) {
this.rabbitTemplate = rabbitTemplate;
}
public void sendMessage(String message) {
rabbitTemplate.convertAndSend("my-exchange", "my-routing-key", message);
}
}
// 消息接收者
@Component
public class MessageReceiver {
@RabbitListener(queues = "my-queue")
public void receiveMessage(String message) {
System.out.println("Received message: " + message);
}
}
```
4. 创建一个启动类:
```java
@SpringBootApplication
public class RabbitMQApplication {
public static void main(String[] args) {
SpringApplication.run(RabbitMQApplication.class, args);
}
}
```
通过以上步骤,你可以在Spring Boot应用中使用RabbitMQ进行消息的发送和接收。你可以
阅读全文