天天看点

消息中间件--RabbitMQ学习(十三)---高级特性之消费端自定义监听

消费端自定义监听

  • 我们一般就是在代码中编写 while循环,进行 consumer.next Deliver方法进行获取下一条消息,然后进行消费处理
  • 但是我们使用自定义的 Consumere更加的方便,解耦性更加的强,也是在实际工作中最常用的使用方式

具体代码实现

消费端代码

public class Consumer {

    public static void main(String[] args) throws Exception{
        //1 创建一个connectionFactory
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.0.159");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        //2通过连接工场创建连接
        Connection connection = connectionFactory.newConnection();
        //3通过connection创建channel
        Channel channel = connection.createChannel();
        //开启消息的确认模式
        channel.confirmSelect();
        String exchangeName = "test_consumer_exchange";
        String routingKey = "consumer.#";
        String queueName = "test_consumer_queue";
        channel.exchangeDeclare(exchangeName,"topic",true,false,null);
        channel.queueDeclare(queueName,true,false,false,null);
        channel.queueBind(queueName,exchangeName,routingKey);
        channel.basicConsume(queueName,true,new MyConsumer(channel));
    }
}
           

生产端代码

public class Producter {
    public static void main(String[] args) throws Exception{
        //1 创建一个connectionFactory
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.0.159");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        //2通过连接工场创建连接
        Connection connection = connectionFactory.newConnection();
        //3通过connection创建channel
        Channel channel = connection.createChannel();
        //开启消息的确认模式
        channel.confirmSelect();
        String exchangeName = "test_consumer_exchange";
        String routingKey = "consumer.save";

        //发送消息
        String msg = "hello";
        channel.basicPublish(exchangeName,routingKey,true,null,msg.getBytes());
    }
}
           

自定义消费者

public class MyConsumer extends DefaultConsumer {
    public MyConsumer(Channel channel) {
        super(channel);
    }

    @Override
    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
        System.err.println("consumerTag:  "+consumerTag);
        System.err.println("envelope  "+envelope);
        System.err.println("properties  "+properties);
        System.err.println("body  "+new String(body));
    }
}