Rabbitmq 延时消息
原理网上一大堆,比我说的清楚,大家可以去看看,这里就不说了。
安装配置
注意 plugins 的处理,因为需要安装一个 rabbitmq_delayed_message_exchange
插件,在 3.7.13
版本中无法使用 rabbitmq-plugins enable rabbitmq_delayed_message_exchange
进行安装,会提示找不到,所以只能自己上 https://www.rabbitmq.com/plugins.html
去下载。
version: '3.1'
services:
rabbitmq:
restart: always
image: rabbitmq:management
container_name: rabbitmq
ports:
- 5672:5672
- 15672:15672
environment:
TZ: Asia/Shanghai
RABBITMQ_DEFAULT_USER: admin
RABBITMQ_DEFAULT_PASS: admin
volumes:
- ./data:/var/lib/rabbitmq
- ./data:/etc/rabbitmq
- ./plugins:/plugins
在处理plugins之后,注意配置一下 enabled_plugins
[rabbitmq_management,rabbitmq_delayed_message_exchange].
使用
配置delayExchange,队列,并且绑定。
@Configuration
public class RabbitConfig {
@Bean
public FanoutExchange delayExchange() {
HashMap<String, Object> args = new HashMap<>();
args.put("x-delayed-type", "direct");
FanoutExchange topicExchange = new FanoutExchange("delay_exchange", true, false, args);
topicExchange.setDelayed(true);
return topicExchange;
}
@Bean
public Queue queue() {
Queue queue = new Queue("delay_queue");
return queue;
}
@Bean
public Binding binding() {
return BindingBuilder.bind(queue()).to(delayExchange());
}
}
发送消息
rabbitTemplate.convertAndSend("delay_exchange", queue, msg, message -> {
message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
// 这里的时间用来设置延时多久
message.getMessageProperties().setHeader("x-delay", 30000);
return message;
});
接收消息
@Component
public class MessageReceiver {
@RabbitListener(queues = "delay_queue")
public void receive(String msg) {
System.out.println("接收到的消息:"+msg);
}
}