spring boot 集成 rabbitmq
时间: 2023-09-11 14:10:34 浏览: 66
可以使用Spring Boot提供的AMQP Starter依赖来集成RabbitMQ。具体步骤如下:
1.添加依赖
在pom.xml文件中添加以下依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
```
2.配置连接信息
在application.properties中配置RabbitMQ的连接信息:
```
spring.rabbitmq.host=<host>
spring.rabbitmq.port=<port>
spring.rabbitmq.username=<username>
spring.rabbitmq.password=<password>
```
3.创建交换机和队列
在配置类中配置交换机和队列:
```
@Bean
public TopicExchange topicExchange() {
return new TopicExchange("myTopicExchange");
}
@Bean
public Queue myQueue() {
return new Queue("myQueue");
}
@Bean
public Binding binding() {
return BindingBuilder.bind(myQueue()).to(topicExchange()).with("myRoutingKey");
}
```
4.发送消息
在发送消息的方法中注入AmqpTemplate,然后发送消息即可:
```
@Autowired
private AmqpTemplate amqpTemplate;
public void send(String message) {
amqpTemplate.convertAndSend("myTopicExchange", "myRoutingKey", message);
}
```
5.接收消息
在接收消息的方法中使用@RabbitListener注解标注方法,并指定队列名:
```
@RabbitListener(queues = "myQueue")
public void receive(String message) {
System.out.println(message);
}
```
以上就是使用Spring Boot集成RabbitMQ的基本步骤。