6、延迟对象模式
前往RabbitMQ官网下载往RabbitMQ添加延迟消息的插件
RabbitMQ官网下载插件的网址:https://www.rabbitmq.com/community-plugins.html
-
把这个插件传输到服务器上
-
根据官网的指示把插件放到RabbitMQ指定的文件夹下
cp rabbitmq_delayed_message_exchange-3.10.0.ez /usr/lib/rabbitmq/lib/rabbitmq_server-3.10.0/plugins/ -
安装延迟队列插件 rabbitmq-plugins enable rabbitmq_delayed_message_exchange
-
重启RabbitMQ systemctl restart rabbitmq-server.service
-
查看插件是否安装成功 进入RabbitMQ的管理页面,进入Exchange的管理页面,新增Exchange,在Type里面可以看到x-delayed-message的选项,证明延迟队列插件安装成功
直接上代码
package com.ken.springbootrqbbitmq.config;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class DelayedQueueConfig {
//队列
public static final String DELAYED_QUEUE_NAME = "delayed_queue";
//交换机
public static final String DELAYED_EXCHANGE_NAME = "DELAYED_EXCHANGE";
//交换机
public static final String DELAYED_ROUTING_KEY = "delayed";
//声明延迟队列
@Bean
public Queue delayedQueue() {
return new Queue(DELAYED_QUEUE_NAME);
}
//声明延迟交换机
@Bean
public CustomExchange delayedExchange() {
Map<String, Object> arguments = new HashMap<>(3);
//设置延迟类型
arguments.put("x-delayed-type","direct");
/**
* 声明自定义交换机
* 第一个参数:交换机的名称
* 第二个参数:交换机的类型
* 第三个参数:是否需要持久化
* 第四个参数:是否自动删除
* 第五个参数:其他参数
*/
return new CustomExchange(DELAYED_QUEUE_NAME,"x-delayed-message",true,false,arguments);
}
//绑定队列和延迟交换机
@Bean
public Binding delayedQueueBindingDelayedExchange(@Qualifier("delayedQueue") Queue delayedQueue,
@Qualifier("delayedExchange") Exchange delayedExchange) {
return BindingBuilder.bind(delayedQueue).to(delayedExchange).with(DELAYED_ROUTING_KEY).noargs();
}
}