第三章-高级特性2:Return消息机制

2019-03-21  本文已影响0人  asfafjwefhfuer

Return消息机制

image.png


/**
 * return listener producer
 *
 * @author yangHX
 * createTime  2019/3/21 22:20
 */
public class Producer {

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = RabbitMqUtil.getConnectionFactory();
        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

        String exchange = "test_return_exchange";
        String routingKey = "return.save";
        String routingKeyError = "abc.save";

        String msg = "Hello RabbitMQ Return Message";

        //return listener
        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("------------handle return ---------------");
                System.err.println("replyCode   :" + replyCode);
                System.err.println("replyText   :" + replyText);
                System.err.println("exchange    :" + exchange);
                System.err.println("routingKey  :" + routingKey);
                System.err.println("properties  :" + properties);
                System.err.println("body        :" + new String(body));
            }
        });

///        channel.basicPublish(exchange, routingKey, true, null, msg.getBytes());
        ///如果消息没被接收。会被删除  mandatory
        channel.basicPublish(exchange, routingKeyError, true, null, msg.getBytes());


    }
}



/**
 * return listener  consumer
 *
 * @author yangHX
 * createTime  2019/3/21 22:19
 */
public class Consumer {

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

        ConnectionFactory connectionFactory = RabbitMqUtil.getConnectionFactory();
        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

        String exchangeName = "test_return_exchange";
        String routingKey = "return.#";
        String queueName = "test_return_queue";
        channel.exchangeDeclare(exchangeName, "topic", true, false, null);
        channel.queueDeclare(queueName, true, false, false, null);
        channel.queueBind(queueName, exchangeName, routingKey);

        QueueingConsumer queueingConsumer = new QueueingConsumer(channel);

        channel.basicConsume(queueName, true, queueingConsumer);

        while (true) {
            QueueingConsumer.Delivery delivery = queueingConsumer.nextDelivery();
            String msg = new String(delivery.getBody());
            System.err.println("return  msg: "+msg);

        }
    }
}



上一篇 下一篇

猜你喜欢

热点阅读