自学内容网 自学内容网

【RabbitMQ】08-延迟消息

1. 延迟消息

在这里插入图片描述

2. 死信交换机

在这里插入图片描述
正常队列不需要接受消息。

@Configuration
public class NormalQueueConfig {
    @Bean
    public DirectExchange normalExchange() {
        return new DirectExchange("normal.direct");
    }
    @Bean
    public Queue normalQueue() {
        return QueueBuilder
                .durable("normal.queue")
                .deadLetterExchange("dlx.direct")
                .build();
    }
    @Bean
    public Binding normalBings(Queue normalQueue, DirectExchange normalExchange) {
        return BindingBuilder.bind(normalQueue).to(normalExchange).with("hi");
    }
}

死信交换机需要key和normalQueue一样。

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "dlx.queue", durable = "true"),
            exchange = @Exchange(name = "dlx.direct", type = ExchangeTypes.DIRECT),
            key = {"hi"}
    ))
    public void listenDlxQueue(String msg) {
        log.info("消费者监听 dlx.message:【{}】", msg);
    }

生产者

    @Test
    void testSendDelayMessage() {
        rabbitTemplate.convertAndSend("normal.direct", "hi", "hello", message ->  {
            message.getMessageProperties().setExpiration("10000");
            return message;
        });
    }

3. DelayExchange插件

在这里插入图片描述
插件

docker volume inspect mq-plugins
docker exec -it mq rabbitmq-plugins enable rabbitmq_delayed_message_exchange

生产者

@Test
    void testDelayMessageByPlugin() {
        rabbitTemplate.convertAndSend("delay.direct", "hi", "hello", message -> {
            message.getMessageProperties().setDelay(10000);
            return message;
        });
    }

消费者

@RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "delay.queue", durable = "true"),
            exchange = @Exchange(name = "delay.direct", delayed = "true"),
            key = {"hi"}
    ))
    public void listenDelayQueue(String msg) {
        log.info("消费者监听到 delay.queue的消息:【{}】", msg);
    }

原文地址:https://blog.csdn.net/qq_45722630/article/details/143694076

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!