一、windows安装
1.下载插件
https://github.com/rabbitmq/rabbitmq-delayed-message-exchange/releases
2.复制插件至rabbitmq安装目录下的plugins目录
3.启用插件,切换至sbin目录下,执行以下命令
rabbitmq-plugins enable rabbitmq_delayed_message_exchange
管理端新增交换机时可以看到这个类型说明启用成功
二、Linux安装
1. 上传.ez文件到plugins目录
2. 执行命令启用插件
rabbitmq-plugins enable rabbitmq_delayed_message_exchange
3. 重启服务
systemctl restart rabbitmq-server
三、java应用场景
1.配置类
import com.great.common.core.constant.RabbitConstant;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.CustomExchange;
import org.springframework.amqp.core.Queue;
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;
/**
* 抢单延迟队列配置
*
* @author great
*/
@Configuration
public class GrabDelayedConfig {
@Bean
public Queue grabQueue() {
return new Queue(RabbitConstant.QUEUE_DELAYED_DISPATCH_GRAB);
}
@Bean
public CustomExchange delayedExchange() {
Map<String, Object> args = new HashMap<>(1);
args.put("x-delayed-type", "direct");
return new CustomExchange(RabbitConstant.EXCHANGE_DELAYED, "x-delayed-message", true, false, args);
}
@Bean
public Binding bindingNotify(@Qualifier("grabQueue") Queue queue,
@Qualifier("delayedExchange") CustomExchange customExchange) {
return BindingBuilder.bind(queue).to(customExchange).with(RabbitConstant.ROUTING_KEY_DISPATCH_GRAB).noargs();
}
}
2.生产者
/**
* 发送延迟消息
* @param message 内容
* @param delayTime 延迟时间(毫秒)
*/
public void sendDelayMessage(Object message, Integer delayTime) {
rabbitTemplate.convertAndSend(RabbitConstant.EXCHANGE_DELAYED, RabbitConstant.ROUTING_KEY_DISPATCH_GRAB, message, a -> {
a.getMessageProperties().setDelay(delayTime);
return a;
});
}
3.消费者
@RabbitListener(queuesToDeclare = @Queue(value = RabbitConstant.QUEUE_DELAYED_DISPATCH_GRAB))
public void receivedDispatchGrabMessage(String message) {
System.out.println("延迟消费:" + message);
}