RabbitMQ发送延时消息

1.整合RabbitMQ

<!--rabbitmq消息队列-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

2.配置文件

rabbitmq:
    host: localhost
    port: 5672
    username: guest
    password: guest
    virtual-host: /
    listener:
      simple:
        acknowledge-mode: manual #手动应答
        concurrency: 5 #消费端最小并发数
        max-concurrency: 10 #消费端最大并发数
        prefetch: 5 #一次请求中预处理的消息数量
    cache:
      channel:
        size: 50 #缓存的channel数量

3.设置配置类

@Configuration
public class MQConfig {

    public static final String DELAY_EXCHANGE = "Ex.DelayExchange";
    public static final String DELAY_QUEUE = "MQ.DelayQueue";
    public static final String DELAY_KEY = "delay.#";

    @Bean
    public TopicExchange delayExchange(){
        Map<String, Object> pros = new HashMap<>();
        // 设置交换机支持延迟消息推送
        pros.put("x-delayed-message", "topic");
        TopicExchange exchange = new TopicExchange(DELAY_EXCHANGE, true, false, pros);
        exchange.setDelayed(true);
        return exchange;
    }

    @Bean
    public Queue delayQueue(){
        return new Queue(DELAY_QUEUE, true);
    }

    @Bean
    public Binding delayBinding(){
        return BindingBuilder.bind(delayQueue()).to(delayExchange()).with(DELAY_KEY);
    }
}

4.消息生产端

@Component
public class MQSender {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    final RabbitTemplate.ConfirmCallback confirmCallback= new RabbitTemplate.ConfirmCallback() {

        public void confirm(CorrelationData correlationData, boolean ack, String cause) {
            System.out.println("correlationData: " + correlationData);
            System.out.println("ack: " + ack);
            if(!ack){
                System.out.println("异常处理....");
            }
        }

    };

    final RabbitTemplate.ReturnCallback returnCallback = new RabbitTemplate.ReturnCallback() {

        public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
            System.out.println("return exchange: " + exchange + ", routingKey: "
                    + routingKey + ", replyCode: " + replyCode + ", replyText: " + replyText);
        }
    };

    // 发送延时消息
    public void sendDelayMessage(Object message) {
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setConfirmCallback(confirmCallback);
        rabbitTemplate.setReturnCallback(returnCallback);
        // UUID 全局唯一
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString().replaceAll("-",""));

        // 发送消息时指定 header 延迟时间
        rabbitTemplate.convertAndSend(MQConfig.DELAY_EXCHANGE, "delay.boot", message,
                new MessagePostProcessor() {
                    @Override
                    public Message postProcessMessage(Message message) throws AmqpException {
                        // 设置消息持久化
                        message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                        // message.getMessageProperties().setHeader("x-delay", "6000");
                        message.getMessageProperties().setDelay(6000);
                        System.err.println("发送消息的时间:" + System.currentTimeMillis());
                        return message;
                    }
                }, correlationData);
    }
}

5.消息消费端

@Component
public class MQReceiver {

    @RabbitListener(queues = "MQ.DelayQueue")
    @RabbitHandler
    public void onDelayMessage(Message msg, Channel channel) throws IOException {
        System.err.println("接收到消息的时间:" + System.currentTimeMillis());
        long deliveryTag = msg.getMessageProperties().getDeliveryTag();
        channel.basicAck(deliveryTag, true);
        System.err.println("接收到的消息:" + new String(msg.getBody()));
    }
}

6.测试

@SpringBootTest
@RunWith(SpringRunner.class)
public class MQSenderTest {

    @Autowired
    private MQSender mqSender;

    @Test
    public void sendDelayMsg() throws  Exception {
        String msg = "发送延时消息";
        mqSender.sendDelayMessage(msg);
    }
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 添加rabbitmq依赖 在pom.xml中添加以下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency> ``` 2. 配置rabbitmq连接信息 在application.properties中添加以下配置: ``` spring.rabbitmq.host=127.0.0.1 spring.rabbitmq.port=5672 spring.rabbitmq.username=guest spring.rabbitmq.password=guest ``` 3. 创建消息队列 在代码中创建消息队列,可以使用@Bean注解进行创建: ``` @Bean public Queue delayQueue() { return new Queue("delay_queue"); } ``` 4. 创建交换机 创建交换机,可以使用@Bean注解进行创建: ``` @Bean public DirectExchange delayExchange() { return new DirectExchange("delay_exchange"); } ``` 5. 绑定队列和交换机 将队列和交换机进行绑定,可以使用@Bean注解进行创建: ``` @Bean public Binding delayBinding() { return BindingBuilder.bind(delayQueue()).to(delayExchange()).with("delay_key"); } ``` 6. 设置延时消息的TTL 设置延时消息的TTL,可以使用@Bean注解进行创建: ``` @Bean public CustomExchange customExchange() { Map<String, Object> args = new HashMap<>(); args.put("x-delayed-type", "direct"); return new CustomExchange("delayed_exchange", "x-delayed-message", true, false, args); } ``` 7. 发送延时消息 发送延时消息,可以使用rabbitTemplate发送消息: ``` rabbitTemplate.convertAndSend("delayed_exchange", "delay_key", message, message1 -> { message1.getMessageProperties().setHeader("x-delay", delayTime); return message1; }); ``` 其中,delayTime为延时时间,单位为毫秒。 完整代码如下: ``` @Configuration public class RabbitmqConfig { @Autowired private RabbitTemplate rabbitTemplate; @Bean public Queue delayQueue() { return new Queue("delay_queue"); } @Bean public DirectExchange delayExchange() { return new DirectExchange("delay_exchange"); } @Bean public Binding delayBinding() { return BindingBuilder.bind(delayQueue()).to(delayExchange()).with("delay_key"); } @Bean public CustomExchange customExchange() { Map<String, Object> args = new HashMap<>(); args.put("x-delayed-type", "direct"); return new CustomExchange("delayed_exchange", "x-delayed-message", true, false, args); } public void sendDelayMessage(Object message, Integer delayTime) { rabbitTemplate.convertAndSend("delayed_exchange", "delay_key", message, message1 -> { message1.getMessageProperties().setHeader("x-delay", delayTime); return message1; }); } } ``` 调用sendDelayMessage方法即可发送延时消息
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值