关闭与RabbitMQ的连接

时间:2018-06-04 09:00:55

标签: java rabbitmq

我创建了一个简单的控制台应用程序,用于侦听Rabbit MQ上的消息。工作良好。没有问题。但是如何关闭连接。我一直在谷歌周围,但我没有找到任何明确的答案。我得到答案的最接近的是这个问题:What is the best way to safely end a java application with running RabbitMQ consumers,但答案省略了最重要的部分:代码!

这是我的代码:

package com.company;

import com.rabbitmq.client.*;

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

interface ObjectRecievedListener {
    void objectRecieved(Object obj);
}

public class RabbitMQReceiver extends RabbitMQBase
{

    ArrayList<DefaultConsumer> consumers = new ArrayList<>();

    private List<ObjectRecievedListener> listeners = new ArrayList<>();
    private final Connection connection;
    private final Channel channel;

    public RabbitMQReceiver(RabbitMQProperties properties) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(properties.getHost());
        factory.setPassword(properties.getPassword());
        factory.setUsername(properties.getLogin());

        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(properties.getInboundQueueName(), true, false, false, null);
        channel.basicQos(1);

        final Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body, "UTF-8");


                try {
                    doWork(message);
                } finally {
                    channel.basicAck(envelope.getDeliveryTag(), false);
                }
            }
        };

        consumers.add((DefaultConsumer) consumer);

        boolean autoAck = false;
        channel.basicConsume(properties.getInboundQueueName(), autoAck, consumer);
    }

    public void addListener(ObjectRecievedListener listener) {
        listeners.add(listener);
    }

    public void stop() {
        try {
            channel.close();
            connection.close();
        } catch (Exception e) {
        }
    }

    private void doWork(String message) {
        Object obj = getObjectFromXML(message);

        for (ObjectRecievedListener l : listeners)
            l.objectRecieved(obj);
        stop();
    }
}

但它并没有因为我致电stop()

而停止

简而言之:如何关闭与Rabbit MQ的连接?

2 个答案:

答案 0 :(得分:0)

RabbitMQ团队监控the rabbitmq-users mailing list,有时只回答StackOverflow上的问题。

如果您说“它没有停止”,您是否确认实际调用了stop()方法?您的代码是否挂在其中一个close()方法上?

channel实例将有一个basicCancel method,您可以在关闭频道和连接之前调用该Performance Tuning来取消当前的消费者。说实话,关闭频道将取消您的消费者,所以我怀疑这是问题的根本原因。

答案 1 :(得分:-1)

试试这个:

let connection = null;

    connection = await amqp.connect(`amqp://${config.username}:${config.password}@${config.host}:${config.port}`);

    connection.close();