我正在尝试编写一个 Perl5 脚本,它每分钟检查一次 MongoDB 服务器的状态,并在它关闭时通知我。欢迎对此任务提出任何建议。目前,我正在使用“MongoDB”模块和“MongoDB::MongoClient”建立连接以查看服务器是否可用。这是基本思想:
while(1)
{
my $conn = connectMongoDB();
if($conn){
sleep 60;
}
else{
sendMail();
last;
}
}
sub connectMongoDB
{
my $client;
eval{ $client = MongoDB::MongoClient->new( host => "mongodb://:\@$server");};
return ($client)?1:0;
}
主要问题是无法断开与服务器的连接。这是cpan页面上的内容:
“没有办法显式断开与数据库的连接。但是,当不存在对 MongoDB::MongoClient 对象的引用时,连接将自动关闭并清理,这发生在 $client 超出范围时(或者如果您取消定义,则更早)它与undef)。”
我试过'undef'和子程序。它们都不会终止连接。由于循环,连接数不断增加。有没有其他方法可以尝试控制连接数?
只要不涉及 crontab,任何其他解决此问题的建议都会受到赞赏。
谢谢。
编辑:
这是睡眠时间设置为 2 秒时的输出,其中 db 版本为 v2.4.4,MongoDB 模块版本为 0.701.4。将 MongoDB 模块升级到 0.702.1 后问题仍然存在。
Fri Aug 16 20:33:06.986 [initandlisten] connection accepted from 127.0.0.1:51031 #3 (1 connection now open)
Fri Aug 16 20:33:08.989 [initandlisten] connection accepted from 127.0.0.1:51033 #4 (2 connections now open)
Fri Aug 16 20:33:10.991 [initandlisten] connection accepted from 127.0.0.1:51034 #5 (3 connections now open)
Fri Aug 16 20:33:12.994 [initandlisten] connection accepted from 127.0.0.1:51035 #6 (4 connections now open)
Fri Aug 16 20:33:14.996 [initandlisten] connection accepted from 127.0.0.1:51036 #7 (5 connections now open)
Fri Aug 16 20:33:16.999 [initandlisten] connection accepted from 127.0.0.1:51038 #8 (6 connections now open)
Fri Aug 16 20:33:19.003 [initandlisten] connection accepted from 127.0.0.1:51039 #9 (7 connections now open)
Fri Aug 16 20:33:21.006 [initandlisten] connection accepted from 127.0.0.1:51040 #10 (8 connections now open)
Fri Aug 16 20:33:23.009 [initandlisten] connection accepted from 127.0.0.1:51042 #11 (9 connections now open)
Fri Aug 16 20:33:25.013 [initandlisten] connection accepted from 127.0.0.1:51043 #12 (10 connections now open)
Fri Aug 16 20:33:27.016 [initandlisten] connection accepted from 127.0.0.1:51044 #13 (11 connections now open)
Fri Aug 16 20:33:29.019 [initandlisten] connection accepted from 127.0.0.1:51045 #14 (12 connections now open)
Fri Aug 16 20:33:31.022 [initandlisten] connection accepted from 127.0.0.1:51047 #15 (13 connections now open)
编辑 2:已解决!
我相信这个问题与 auto_connect 选项有关。一旦它被禁用,代码就可以正常工作。下面是目前有效的东西。
sub connectMongoDB
{
my $client;
eval{
$client = MongoDB::MongoClient->new( host => "mongodb://:\@$server",
auto_connect => 0);
$client->connect;
};
return (!$@)?1:0;
}
最好的