未关闭与MongoDB的连接时会发生什么? [英] What happens when connections to MongoDB are not closed?

查看:115
本文介绍了未关闭与MongoDB的连接时会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下PHP脚本,该脚本基本上连接到MongoDB,编写文档,然后关闭连接19000次:

I have the following PHP script that basically connects to the MongoDB, writes a document and then closes the connection 19000 times:

<?php
for($i=0; $i < 19000; $i++) {
    $con = new Mongo("mongodb://localhost:27017");
    $db = $con->selectDB('test');

    $col = $db->selectCollection('close_wait_test');
    $col->insert(array('Test' => 'Value1'));

    $con->close();
}
?>

运行该脚本一次可以正常工作,但是如果我几秒钟后运行该脚本,则会收到无法分配请求的地址"异常,这可以理解,因为服务器系统可能已用尽端口.

Running this script once works fine, but if I run the script a few seconds later, I get the 'Cannot assign requested address' exception, which is understandable as the server system probably ran out of ports.

但是,如果我删除了$ con-> close();我可以一遍又一遍地运行该脚本,而不会对数据库造成任何明显的负担.我假设这是因为与数据库的连接是持久的,并且在脚本上重复使用了相同的初始连接.

If however, I remove $con->close(); I can run that script over and over again without any noticeable strain on the database. I'm assuming this is because the connect to the database is persistent and reuses the same initial connection on the script.

我想知道的是,如果有2万多名不同的用户同时运行1个该脚本循环,那么数据库将如何处理?例如每个用户需要创建一个到数据库的连接,可用的连接是否会简单用完?还是所有这些用户都使用第一个用户创建的相同初始连接?

What I'd like to know is if 20k+ different users ran 1 loop of this script at the same time, what would happen to the database? e.g. would the available connections simply run out because each user need creates one connections to the database? or would all those users be using the same initial connection created by the first user?

推荐答案

您不应在每次迭代时都调用-> close().如果调用close,则告诉驱动程序不要重用持久连接.如果以严格的循环运行它,则操作系统将用尽所有端口,因为它们都处于TIME_WAIT状态.

You should not be calling ->close() on every iteration. If you call close, you tell the driver to not reuse a persistent connection. If you run this in a tight loop, then the OS runs out of ports to use, as they are all in TIME_WAIT state.

PHP驱动程序使用持久连接,并且(如不带示例)在紧密循环中运行(不调用-> close)"new Mongo",驱动程序将进行新连接并重用已经存在的一个.

The PHP driver uses persistent connections, and if (without calling ->close) you run "new Mongo" in a tight loop like in your example, the driver will not make new connections and reuse the already existing one.

这篇关于未关闭与MongoDB的连接时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆