参考链接:https://docs.spring.io/spring-amqp/docs/2.1.5.RELEASE/reference/#delayed-message-exchange
安装插件 rabbitmq_delayed_message_exchange
1.下载RabbitMQ的插件
https://www.rabbitmq.com/community-plugins.html
2.解压插件到rabbitmq的目录plugins
3.编辑文件
enabled_plugins
,添加插件到这个文件
[rabbitmq_management,rabbitmq_delayed_message_exchange].
Springboot发送延迟消息
-
pom.xml
添加依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
-
application.yml
配置
spring:
rabbitmq:
host: localhost
port: 5672
username: admin
password: admin
virtual-host: /
- 设置exchange的delayed属性
@Configuration
public class RabbitMqConfig {
@Bean
public TopicExchange exchange() {
TopicExchange exchange = new TopicExchange("ex.delayed.message", true, false);
//todo: 1
exchange.setDelayed(true);
return exchange;
}
@Bean
public Binding binding(TopicExchange exchange, Queue queue) {
return BindingBuilder.bind(queue).to(exchange).with("rk.delayed");
}
@Bean
public Queue queue() {
return new Queue("queue.delayed", true, false, false);
}
}
- 消息的监听器:
@Component
public class QueueListener {
@RabbitListener(queues = "queue.delayed")
public void processMessage(String content) {
System.out.println("process message: " + content);
System.out.println("current date:" + DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
}
}
- 发送消息的时候指定延迟的时间
@Test
public void sendDelayedMessage() {
MessageProperties properties = new MessageProperties();
properties.setDelay(10000); //延迟10秒
properties.setContentType("text");
String msg = "This is a delayed message,current date:"
+ DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
Message message = MessageBuilder
.withBody(msg.getBytes())
.andProperties(properties)
.build();
rabbitTemplate.convertAndSend("ex.delayed.message", "rk.delayed", message);
}
网友评论