spring Boot 给 x-delayed-message 类型的RabbitMq 发 延时消息
时间: 2024-02-25 13:56:57 浏览: 45
是的,Spring Boot 可以给 `x-delayed-message` 类型的 RabbitMQ 发送延时消息。具体实现方式如下:
1. 在 `pom.xml` 文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
<version>2.2.13.RELEASE</version>
</dependency>
```
2. 在 RabbitMQ 中创建一个 `x-delayed-message` 类型的 Exchange,如下所示:
```bash
$ rabbitmqctl add_exchange delayed_exchange --type=x-delayed-message --arguments='{"x-delayed-type":"direct"}'
```
3. 在 Spring Boot 的配置文件中添加以下配置:
```yaml
spring:
rabbitmq:
addresses: <RabbitMQ地址>
username: <RabbitMQ用户名>
password: <RabbitMQ密码>
publisher-confirm-type: correlated
publisher-returns: true
virtual-host: /
template:
exchange: delayed_exchange
routing-key: <路由键>
```
4. 在 Spring Boot 应用中使用 `AmqpTemplate` 发送延时消息,如下所示:
```java
@Autowired
private AmqpTemplate amqpTemplate;
public void sendDelayedMessage(String message, long delayTime) {
MessagePostProcessor messagePostProcessor = message1 -> {
message1.getMessageProperties().setHeader("x-delay", delayTime);
return message1;
};
amqpTemplate.convertAndSend(messagePostProcessor);
}
```
其中,`delayTime` 参数表示延时时间,单位为毫秒。
使用上述方法,就可以给 `x-delayed-message` 类型的 RabbitMQ 发送延时消息了。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)