spring boot 怎么配置rabbittemplate
时间: 2023-09-13 14:10:33 浏览: 91
可以在application.properties或application.yml文件中添加以下配置:
Spring Boot 1.x 版本:
```
spring.rabbitmq.host=your_rabbitmq_host
spring.rabbitmq.port=your_rabbitmq_port
spring.rabbitmq.username=your_rabbitmq_username
spring.rabbitmq.password=your_rabbitmq_password
```
Spring Boot 2.x 版本:
```
spring.rabbitmq.host=your_rabbitmq_host
spring.rabbitmq.port=your_rabbitmq_port
spring.rabbitmq.username=your_rabbitmq_username
spring.rabbitmq.password=your_rabbitmq_password
spring.rabbitmq.template.default-receive-queue=your_default_receive_queue
```
还可以添加以下可选属性:
```
spring.rabbitmq.virtual-host=your_rabbitmq_vhost # 虚拟主机,默认为 /
spring.rabbitmq.connection-timeout=6000 # 连接超时时间,默认为 6000 毫秒
spring.rabbitmq.template.exchange=your_exchange_name # 默认交换机名称,默认为空
spring.rabbitmq.template.routing-key=your_routing_key # 默认路由键,默认为队列名称
spring.rabbitmq.listener.simple.auto-startup=true # 启动时是否自动启动监听器,默认为 true
```
在代码中使用RabbitTemplate发送消息:
```
@Autowired
private RabbitTemplate rabbitTemplate;
public void send(String message) {
rabbitTemplate.convertAndSend(your_exchange_name, your_routing_key, message);
}
```
在代码中监听消息:
```
@RabbitListener(queues = your_queue_name)
public void onMessage(String message) {
System.out.println("Received message: " + message);
}
```
阅读全文