spring boot 集成rabbitmq
时间: 2023-09-11 15:09:04 浏览: 282
要在Spring Boot中使用RabbitMQ,您需要添加以下依赖项到您的`pom.xml`文件中:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
```
接下来,您需要在`application.properties`文件中添加以下配置:
```properties
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
```
这指定了RabbitMQ服务器的主机和端口以及访问凭据。
现在,您可以创建一个简单的RabbitMQ生产者和消费者:
```java
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class RabbitMQService {
private final RabbitTemplate rabbitTemplate;
@Autowired
public RabbitMQService(RabbitTemplate rabbitTemplate) {
this.rabbitTemplate = rabbitTemplate;
}
public void sendMessage(String message) {
rabbitTemplate.convertAndSend("myExchange", "myRoutingKey", message);
}
@RabbitListener(queues = "myQueue")
public void receiveMessage(String message) {
System.out.println("Received message: " + message);
}
}
```
这个例子中,RabbitMQService类包含了`RabbitTemplate`和`@RabbitListener`注解。`RabbitTemplate`用于发送消息到RabbitMQ服务器,`@RabbitListener`用于监听消息,并在消息到达时执行方法。
最后,您可以在您的应用程序中使用RabbitMQService类:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyApp {
private final RabbitMQService rabbitMQService;
@Autowired
public MyApp(RabbitMQService rabbitMQService) {
this.rabbitMQService = rabbitMQService;
}
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
public void sendMessageToRabbitMQ() {
rabbitMQService.sendMessage("Hello, RabbitMQ!");
}
}
```
在这个例子中,`MyApp`类注入了`RabbitMQService`,并使用`sendMessageToRabbitMQ()`方法发送消息到RabbitMQ服务器。当消息到达时,`@RabbitListener`注解的`receiveMessage()`方法将被执行。
阅读全文