rabbitMQ整合springboot,配置文件编写
时间: 2023-07-07 12:42:35 浏览: 137
springboot+rabbitmq 集成
好的,下面是RabbitMQ整合Spring Boot的配置文件编写:
1. 首先,在pom.xml中添加RabbitMQ依赖:
```xml
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
<version>2.2.4.RELEASE</version>
</dependency>
```
2. 在application.yml中配置RabbitMQ连接信息:
```yaml
spring:
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
```
3. 创建一个RabbitMQ配置类,用于配置RabbitMQ的连接工厂、交换机、队列等信息:
```java
@Configuration
public class RabbitMQConfig {
// 定义队列名称
public static final String QUEUE_NAME = "test_queue";
// 定义交换机名称
public static final String EXCHANGE_NAME = "test_exchange";
// 定义路由键
public static final String ROUTING_KEY = "test_routing_key";
// 定义队列
@Bean
public Queue queue() {
return new Queue(QUEUE_NAME, true, false, false);
}
// 定义交换机
@Bean
public Exchange exchange() {
return new DirectExchange(EXCHANGE_NAME, true, false);
}
// 将队列与交换机绑定,并指定路由键
@Bean
public Binding binding() {
return BindingBuilder.bind(queue()).to(exchange()).with(ROUTING_KEY).noargs();
}
// 创建连接工厂
@Bean
public ConnectionFactory connectionFactory() {
CachingConnectionFactory factory = new CachingConnectionFactory();
factory.setHost("localhost");
factory.setPort(5672);
factory.setUsername("guest");
factory.setPassword("guest");
return factory;
}
// 创建RabbitMQ模板
@Bean
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
return rabbitTemplate;
}
}
```
4. 在需要使用RabbitMQ的地方注入RabbitMQ模板,并发送消息:
```java
@Service
public class MessageService {
@Autowired
private RabbitTemplate rabbitTemplate;
public void sendMessage(String message) {
rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME, RabbitMQConfig.ROUTING_KEY, message);
}
}
```
这样就完成了RabbitMQ和Spring Boot的整合,可以通过RabbitMQ发送和接收消息了。
阅读全文