rabbitmq延迟队列的实现

第一步:下载延迟队列插件

去https://github.com/rabbitmq/rabbitmq-delayed-message-exchange/tree/v3.9.x中下载对应版本的插件

 rabbitmq延迟队列的实现_第1张图片

第二步:安装

执行 rabbitmq-plugins enable rabbitmq_delayed_message_exchange 命令

出现了x-delayed-message就代表安装成功

http://localhost:15672/

rabbitmq延迟队列的实现_第2张图片第三步:pom文件导入


    com.rabbitmq
    amqp-client


    org.springframework.amqp
    spring-rabbit

第四步 :创建交换机并绑定延迟队列

package com.flexible.yiren.user.rabbitmq;


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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitConfig {
    public static final String DELAY_EXCHANGE = "delay.exchange";

    public static final String DELAY_ROUTE_KEY = "delay.routeKey";

    public static final String DELAY_QUEUE = "delay.queue";

    /**
     * 延时交换机
     * @return 延时交换机
     */
    @Bean
    public CustomExchange delayExchange() {
        Map arguments = new HashMap<>(1);
        arguments.put("x-delayed-type", "direct");
        return new CustomExchange(DELAY_EXCHANGE,"x-delayed-message",true,false,arguments);
    }

    /**
     * mq已经安装了延时插件使用,否则得使用延时插件
     * @return 延时发送队列。
     */
    @Bean
    public Queue delayQueue() {
        return new Queue(DELAY_QUEUE,true,false,false);
    }

    /**
     * 延时绑定区
     * @return 延时绑定区
     */
    @Bean
    public Binding delayBind() {
        return BindingBuilder.bind(this.delayQueue()).to(this.delayExchange()).with(DELAY_ROUTE_KEY).noargs();
    }

}

 第五步:创建一个监听队列的方法

package com.flexible.yiren.user.rabbitmq;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class CouponHandler {


    @RabbitHandler
    @RabbitListener(queues = RabbitConfig.DELAY_QUEUE)
    public void delayConsumer(Message message) {
        System.out.println("-------"+new String(message.getBody()));
    }


}

 第六步:发送内容

package com.flexible.yiren.user.contorller;


import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;


@RestController
@RequiredArgsConstructor
public class CouponsController {


    private final RabbitTemplate rabbitTemplate;
    
    @GetMapping("test")
    public void test() {
        rabbitTemplate.convertAndSend(RabbitConfig.DELAY_EXCHANGE, RabbitConfig.DELAY_ROUTE_KEY, "需要发送的消息内容", msg -> {
            msg.getMessageProperties().setHeader("x-delay", 2 * 1000);//延迟两秒接收
            return msg;
        });

    }
}

你可能感兴趣的:(java)