gpt4 book ai didi

java - 正确关闭 RabbitMQ channel 和连接

转载 作者:行者123 更新时间:2023-12-05 06:38:33 28 4
gpt4 key购买 nike

我目前正在运行一个基本的 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 方法时,它都会发布,然后 channel 和连接都关闭,以防止新 channel 和连接每 3 秒卡在内存中。

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

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

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

最佳答案

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.

我认为你的连接有问题。

检查操作系统中的 TCP 连接,例如:


1. 网络统计-anp | grep:5672 | grep 已建立 | wc -l

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


2. rabbitmqctl 列表连接
如果您在 12 中有很多连接,则意味着您没有以正确的方式关闭连接/ channel 。

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

例如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是关闭连接

关于java - 正确关闭 RabbitMQ channel 和连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45800701/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com