正确关闭 RabbitMQ 通道和连接

Close RabbitMQ channels and connections properly

我目前运行一个基本的RabbitMQ主题发布,每3秒发布一次。

我的 class 看起来像这样:

import com.rabbitmq.client.*;

import java.io.IOException;

public class EmitLogTopic {

    private static final String EXCHANGE_NAME = "topic_logs";

    @Scheduled(fixedRate = 3000)
    public void publish(String[] argv)
                  throws Exception {

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME, "topic");

        String routingKey = getRouting(argv);
        String message = getMessage(argv);

        channel.basicPublish(EXCHANGE_NAME, routingKey, null, message.getBytes());
        System.out.println(" [x] Sent '" + routingKey + "':'" + message + "'");

        channel.close();
        connection.close();
    }
    //...
}

我希望每次运行 publish 方法时,它都会发布,然后通道和连接都关闭,防止每 3 秒有一个新的通道和连接卡在内存中。

但是,当我查看我的 RabbitMQ 管理界面(在概览页面)时,“全局计数”部分显示连接总数和通道总数都在不断增加。

最终,由于达到套接字限制和内存限制,我的应用程序崩溃了。

所以看起来 close() 并没有删除使用的通道和连接,而是仍然将它们保留在内存中,最终导致所有内存被消耗。在通道和连接上使用什么方法可以确保它们不会这样做?

However, when I look at my RabbitMQ admin interface (at the overview page), the Global Counts section shows that both the total number of connections and channels keep on increasing.

我认为你的连接有问题。

检查 OS 中的 TCP 连接,例如:

1. netstat -anp | grep :5672 | grep ESTABLISHED | wc -l

同时使用命令行工具检查您的连接:

2. rabbitmqctl list_connections 如果您在 12 中有很多连接意味着您没有以正确的方式关闭 connections/channels。

如果您需要处理大量连接,您可以增加文件描述符配置:

例如https://www.rabbitmq.com/install-debian.html

使用 systemd(最近的 Linux 发行版)

On distributions that use systemd, the OS limits are controlled via a configuration file at /etc/systemd/system/rabbitmq-server.service.d/limits.conf, for example:

[Service] LimitNOFILE=300000

编辑

您发布的代码很好,close() 方法是关闭连接的正确方法。

如果你执行代码,你应该在你的真实代码中进行调查。

还要检查日志中是否有:

=INFO REPORT==== 22-Aug-2017::09:23:28 ===
connection <0.383.0> ([::1]:60590 -> [::1]:5672): user 'guest' authenticated and granted access to vhost '/'

=INFO REPORT==== 22-Aug-2017::09:23:37 ===
closing AMQP connection <0.383.0> ([::1]:60590 -> [::1]:5672, vhost: '/', user: 'guest')

closing AMQP connection是关闭连接