美文网首页
RabbitMQ实现延迟消息

RabbitMQ实现延迟消息

作者: Herman7z | 来源:发表于2019-05-05 22:46 被阅读0次

    参考链接:https://docs.spring.io/spring-amqp/docs/2.1.5.RELEASE/reference/#delayed-message-exchange

    安装插件 rabbitmq_delayed_message_exchange

    1.下载RabbitMQ的插件
    https://www.rabbitmq.com/community-plugins.html

    image.png
    2.解压插件到rabbitmq的目录plugins
    3.编辑文件enabled_plugins,添加插件到这个文件
    [rabbitmq_management,rabbitmq_delayed_message_exchange].
    

    Springboot发送延迟消息

    1. pom.xml添加依赖
     <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-amqp</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
        </dependencies>
    
    1. application.yml 配置
    spring:
      rabbitmq:
        host: localhost
        port: 5672
        username: admin
        password: admin
        virtual-host: /
    
    1. 设置exchange的delayed属性
    @Configuration
    public class RabbitMqConfig {
        @Bean
        public TopicExchange exchange() {
            TopicExchange exchange = new TopicExchange("ex.delayed.message", true, false);
            //todo: 1
            exchange.setDelayed(true);
            return exchange;
        }
        @Bean
        public Binding binding(TopicExchange exchange, Queue queue) {
            return BindingBuilder.bind(queue).to(exchange).with("rk.delayed");
        }
        @Bean
        public Queue queue() {
            return new Queue("queue.delayed", true, false, false);
        }
    }
    
    
    1. 消息的监听器:
    @Component
    public class QueueListener {
    
        @RabbitListener(queues = "queue.delayed")
        public void processMessage(String content) {
            System.out.println("process message: " + content);
            System.out.println("current date:" + DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        }
    
    }
    
    1. 发送消息的时候指定延迟的时间
      @Test
        public void sendDelayedMessage() {
            MessageProperties properties = new MessageProperties();
            properties.setDelay(10000); //延迟10秒
            properties.setContentType("text");
    
            String msg = "This is a delayed message,current date:"
                    + DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
            Message message = MessageBuilder
                    .withBody(msg.getBytes())
                    .andProperties(properties)
                    .build();
            rabbitTemplate.convertAndSend("ex.delayed.message", "rk.delayed", message);
        }
    
    

    事例项目地址:https://gitee.com/silentwu/rabbitmq-delayed-message

    相关文章

      网友评论

          本文标题:RabbitMQ实现延迟消息

          本文链接:https://www.haomeiwen.com/subject/mqgkoqtx.html