RabbitMQ实现延迟消息

参考链接: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添加依赖
 
        
            org.springframework.boot
            spring-boot-starter-amqp
        
        
            org.springframework.boot
            spring-boot-starter-web
        
    
  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实现延迟消息)