springboot整合rabbitmq配置 延时消息队列
时间: 2023-06-02 14:02:45 浏览: 232
springboot实现rabbitmq的队列初始化和绑定
1. 添加rabbitmq依赖
在pom.xml中添加以下依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
```
2. 配置rabbitmq连接信息
在application.properties中添加以下配置:
```
spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
```
3. 创建消息队列
在代码中创建消息队列,可以使用@Bean注解进行创建:
```
@Bean
public Queue delayQueue() {
return new Queue("delay_queue");
}
```
4. 创建交换机
创建交换机,可以使用@Bean注解进行创建:
```
@Bean
public DirectExchange delayExchange() {
return new DirectExchange("delay_exchange");
}
```
5. 绑定队列和交换机
将队列和交换机进行绑定,可以使用@Bean注解进行创建:
```
@Bean
public Binding delayBinding() {
return BindingBuilder.bind(delayQueue()).to(delayExchange()).with("delay_key");
}
```
6. 设置延时消息的TTL
设置延时消息的TTL,可以使用@Bean注解进行创建:
```
@Bean
public CustomExchange customExchange() {
Map<String, Object> args = new HashMap<>();
args.put("x-delayed-type", "direct");
return new CustomExchange("delayed_exchange", "x-delayed-message", true, false, args);
}
```
7. 发送延时消息
发送延时消息,可以使用rabbitTemplate发送消息:
```
rabbitTemplate.convertAndSend("delayed_exchange", "delay_key", message, message1 -> {
message1.getMessageProperties().setHeader("x-delay", delayTime);
return message1;
});
```
其中,delayTime为延时时间,单位为毫秒。
完整代码如下:
```
@Configuration
public class RabbitmqConfig {
@Autowired
private RabbitTemplate rabbitTemplate;
@Bean
public Queue delayQueue() {
return new Queue("delay_queue");
}
@Bean
public DirectExchange delayExchange() {
return new DirectExchange("delay_exchange");
}
@Bean
public Binding delayBinding() {
return BindingBuilder.bind(delayQueue()).to(delayExchange()).with("delay_key");
}
@Bean
public CustomExchange customExchange() {
Map<String, Object> args = new HashMap<>();
args.put("x-delayed-type", "direct");
return new CustomExchange("delayed_exchange", "x-delayed-message", true, false, args);
}
public void sendDelayMessage(Object message, Integer delayTime) {
rabbitTemplate.convertAndSend("delayed_exchange", "delay_key", message, message1 -> {
message1.getMessageProperties().setHeader("x-delay", delayTime);
return message1;
});
}
}
```
调用sendDelayMessage方法即可发送延时消息。
阅读全文