mysql 几次连接后连接时间过长

mysql connection taking too long after a few connections

我在 Centos 7 上有 Mysql 5.7 这里是 my.cnf:

datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock

key_buffer_size = 512M
query_cache_type = 1
query_cache_size = 1024M
tmp_table_size = 32M
innodb_buffer_pool_size = 2048M
##innodb_additional_mem_pool_size = 10M
innodb_log_buffer_size = 8M
max_connections = 250
sort_buffer_size = 64M

long_query_time = 5
slow_query_log = 1
skip-name-resolve

如你所见,我有 skip-name-resolve 反正我做了 test.php:

<?php

for ($i = 0;$i<1000;$i++) {
    $t1 = microtime(true);
    $conn = new \mysqli("xx.xx.xx.xxx","xxxxxxx","xxxxxx","xxxx");
    $t2 = microtime(true);
    echo "connection: ". floatval($t2 - $t1). PHP_EOL;

    $t3 = microtime(true);
    $query = $conn->query("SELECT 1");
    $t4 = microtime(true);
    echo "query: ".$i.") ". floatval($t4-$t3) . PHP_EOL;
    $conn->close();
}

当我 运行 这个 test.php 在第 65 次循环后,我看到连接持续时间增加到 1 秒甚至 3 秒这是示例输出:

...
...
query: 62) 0.0028440952301025
connection: 0.0020878314971924
query: 63) 0.002816915512085
connection: 0.002126932144165
query: 64) 0.002856969833374
connection: 1.0042409896851
query: 65) 0.013001918792725
connection: 1.0027761459351
query: 66) 0.01302695274353
connection: 1.002720117569
query: 67) 0.012753009796143
connection: 1.003103017807
query: 68) 0.012816905975342
connection: 1.0031731128693
query: 69) 0.012447118759155
connection: 1.003485918045
query: 70) 0.012918949127197
...
...

每次我 运行 这个 test.php 结果都是一样的,总是在第 65 次循环后将连接时间增加到不可接受的时间。我真的很困惑。有人知道吗?

此致。

你不应该创建那么多连接,而应该只创建一个:

$conn = new mysqli("xx.xx.xx.xxx","xxxxxxx","xxxxxx","xxxx");

for ($i = 0;$i<1000;$i++) {
    $t1 = microtime(true);

    $t2 = microtime(true);
    echo "connection: ". floatval($t2 - $t1). PHP_EOL;

    $t3 = microtime(true);
    $query = $conn->query("SELECT 1");
    $t4 = microtime(true);
    echo "query: ".$i.") ". floatval($t4-$t3) . PHP_EOL;
}

$conn->close();

我们解决了与 mysql 服务器本身无关的问题。问题是 centos7 的主机名,鉴于主机名不是真实的,所以 OS 试图解决它们并且花费了太长时间有两个解决方案:

1) 使用本地主机

设置它们
hostnamectl --transient set-hostname "localhost"

2) 将你的假主机名重定向到本地主机,假设 mysql-server1.mydomain.com 是主机名服务器

echo 127.0.0.1 mysql-server1.mydomain.com > /etc/hosts