RabbitMQ

RabbitMQ高级特性-2.消费端自定义监听

2021-12-14  本文已影响0人  那钱有着落吗

在之前我们都是需要在while循环里面去不断的去接受监听消息,接受消息,还有一种更优雅的方式就是使用自定义的消费者

下面是代码:
producer与之前无异:

public static void main(String[] args) throws IOException, TimeoutException {

        //1 创建ConnectionFactory
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        //2 获取Connection
        Connection connection = connectionFactory.newConnection();

        //3 通过Connection创建一个新的Channel
        Channel channel = connection.createChannel();


        //4 指定我们的消息投递模式: 消息的确认模式
        channel.confirmSelect();
        String exchangeName = "custom_exchange";
        String routingKey = "custom.save";

        //5 发送一条消息
        String msg = "Hello RabbitMQ Send custom message!";


        for(int i=0;i<5;i++){
            channel.basicPublish(exchangeName, routingKey, null, msg.getBytes());
        }

    }

consumer:

public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
//1 创建ConnectionFactory
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        //2 获取Connection
        Connection connection = connectionFactory.newConnection();

        //3 通过Connection创建一个新的Channel
        Channel channel = connection.createChannel();

        String exchangeName = "custom_exchange";
        String routingKey = "custom.#";
        String queueName = "custom_queue";

        //4 声明交换机和队列 然后进行绑定设置, 最后制定路由Key
        channel.exchangeDeclare(exchangeName, "topic", true);
        channel.queueDeclare(queueName, true, false, false, null);
        channel.queueBind(queueName, exchangeName, routingKey);

        //5 创建消费者
        channel.basicConsume(queueName, true, new MyConsumer(channel));

    }

MyConsumer:


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("-----consume message------");
        System.out.println("consumerTag:"+consumerTag);
        System.out.println("envelope:"+envelope);
        System.out.println("properties:"+properties);
        System.out.println("body:"+new String(body));

    }
}
上一篇下一篇

猜你喜欢

热点阅读