如上一篇死信队列,在消息属性上设置TTL的方式,消息可能不会按时死亡,RabbitMQ只会检查第一个消息是否过期,如果过期就会丢到死信队列,如果第一个消息延时时间很长,而第二个消息延时时间很短,第二个消息则不会得到优先执行。这里利用插件实现延迟队列。
插件下载地址
https://www.rabbitmq.com/community-plugins.html
下载文件放在服务器/usr/lib/rabbitmq/lib/rabbitmq_server-3.11.3/plugins下然后再shell中运行
rabbitmq-plugins enable rabbitmq_delayed_message_exchange
//重启
systemctl restart rabbitmq-server
Configuration配置类
@Configuration
public class Rabbimq2 {
@Bean
public CustomExchange customExchange(){
Map map=new HashMap<>();
map.put("x-delayed-type","direct");
return new CustomExchange("exchange5","x-delayed-message",true,false,map);
}
@Bean
public Queue queue(){
return new Queue("queue5",true,false,false);
}
@Bean
public Binding binding(){
return BindingBuilder.bind(queue()).to(customExchange()).with("123").noargs();
}
}
生产者
@Test
void contextLoads() {
MessageProperties messageProperties=new MessageProperties();
messageProperties.setDelay(40000);
Message message1=new Message("hello".getBytes(),messageProperties);
rabbitTemplate.convertAndSend("exchange5","123",message1);
}
@Test
void test(){
MessageProperties messageProperties1=new MessageProperties();
messageProperties1.setDelay(20000);
Message message2=new Message("jk".getBytes(),messageProperties1);
rabbitTemplate.convertAndSend("exchange5","123",message2);
}
消费者
@Component
public class rabbitmq {
@RabbitListener(queues = "queue5")
public void consume(String msg, Message message, Channel channel){
System.out.println(msg);
}
}
客户端通过配置队列的x-max-priority参数的方式设置一个队列支持的最大优先级以此来声明一个优先级队列。优先级最大值为255、最小值为0(默认值),推荐1~10。生产者可以通过设置priority属性设置消息的优先级(值越大,优先级越高)。优先级越高,越先被消费者消费,但是带来的内存、磁盘、CPU开销越高。
Configuration配置
@Configuration
public class DirectExchange1 {
@Bean
public Queue queue(){
Map map=new HashMap<>();
map.put("x-max-priority",10);
return new Queue("queue6",true,false,false,map);
}
@Bean
public DirectExchange directExchange(){
return new DirectExchange("exchange6",true,false);
}
@Bean
Binding binding(){
Binding binding= BindingBuilder.bind(queue()).to(directExchange()).with("123");
return binding;
}
}
生产者
@Test
void test(){
for(int i=0;i<10;i++){
if(i==5){
rabbitTemplate.convertAndSend("exchange6","123","hello"+i,message ->{
MessageProperties messageProperties=message.getMessageProperties();
messageProperties.setPriority(5);
return message;
} );
}
else {
rabbitTemplate.convertAndSend("exchange6","123","hello"+i,message ->{
MessageProperties messageProperties=message.getMessageProperties();
messageProperties.setPriority(1);
return message;
} );
}
}
}