消费端自定义监听

本文介绍如何在RabbitMQ中使用自定义消费监听处理消息。通过创建并继承DefaultConsumer类,重写handleDelivery方法,可以高效地实现消息消费。示例代码展示了生产者发布消息到指定交换机及消费者绑定队列并消费消息的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

之前的例子里,我们消费者监听消费消息都是下面这样写的,一个while死循环,然后consumer.nextDelivery()一个个获取消息 。(初学者傻傻方式,哈哈)

在这里插入图片描述
后面我们就可以通过自定义消费监听者,来实现消息的消费了

步骤:

  1. 创建一个自定义的消息处理类(如MyConsumer类)
  2. 继承DefaultConsumer
  3. 重写handleDelivery方法
代码:

生产者

package com.vivo.demo1.consumer;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author:luzaichun
 * @Date:2020/12/22
 * @Time:23:34
 **/
public class Producer {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setVirtualHost("/");
        factory.setPort(5672);
        factory.setHost("192.168.3.7");

        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.addReturnListener(new ReturnListener() {
            @Override
            public void handleReturn(int replyCode, String replyText, String exchange, String routingKey, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消息路由到queue失败。body=" + new String(body));
            }
        });
        for (int i = 0; i < 3; i++) {
            channel.basicPublish("test_exchange", "test.abc", true, null, "自定义消费监听测试".getBytes());
        }

    }
}

消费者

package com.vivo.demo1.consumer;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author:luzaichun
 * @Date:2020/12/22
 * @Time:23:38
 **/
public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setVirtualHost("/");
        factory.setPort(5672);
        factory.setHost("192.168.3.7");

        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare("test_exchange","topic",false,false,null);
        channel.queueDeclare("test_queue",false,false,false,null);
        channel.queueBind("test_queue","test_exchange","test.#");

        //偷懒可以直接new一个DefaultConsumer,然后Override里面的handleDelivery方法
        /*channel.basicConsume("test_queue",true,new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                super.handleDelivery(consumerTag, envelope, properties, body);
                System.out.println("body="+new String(body));
            }
        });*/

        //创建一个MyConsumer类,继承DefaultConsumer,重写handleDelivery方法
        channel.basicConsume("test_queue",true,new MyConsumer(channel));
    }
}

消费监听处理类

	package com.vivo.demo1.consumer;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

import java.io.IOException;

/**
 * @author:luzaichun
 * @Date:2020/12/22
 * @Time:23:50
 **/
public class MyConsumer extends DefaultConsumer {
    /**
     * Constructs a new instance and records its association to the passed-in channel.
     *
     * @param channel the channel to which this consumer is attached
     */
    public MyConsumer(Channel channel) {
        super(channel);
    }

    @Override
    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
        super.handleDelivery(consumerTag, envelope, properties, body);
        System.out.println("获取到消息=======");
        System.out.println("envelope="+ JSONObject.toJSONString(envelope));
        System.out.println("body="+new String(body));
    }
}

测试结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值