简体   繁体   中英

PHP remote MySQL database connection is very SLOW

I have 2 servers on different geographical locations Singapore and India.

I need to connect server 1 from a php script at server 2. script looks like this:

<?php 

echo microtime(true)."\n";
$con = mysql_pconnect('server1','username','password');

$db = mysql_select_db('database_name',$con);                      

echo microtime(true)."\n";

$q = "select * from tablename where id='35'";
$result = mysql_query($q);

echo microtime(true)."\n";

?>

The out put of this script is like this:

1373977322.9081
1373977324.377
1373977324.6625

As you can see the time between the 2nd and 3rd is around 2 seconds, which means is taking more 2 seconds. 花费了更多的2秒。 And time between 3rd and 4th(select query) is very less.

Also if I run this script on server1 connecting it to server1 itself it takes 20 ms.

Can't figure out why connection time is soo long. I have also tried some things like and persistent connections. 和持久连接。 but :(

How can I debug this thing???

As you can see from the timings, opening a connection takes 1.4689 seconds, and the query takes 0.2855 seconds. If a one-time DNS lookup was the only issue the query would be over a lot faster: 300ms is a really long time. This means the problem must be somewhere else.

When the connection is first opened the client and the server go through a negotiation where one asks the other a question and then waits for a reply, many times. If the network has high latency each question-answer cycle takes a non-trivial amount of time, and that adds up. You could use ping to measure the network latency between the two machines.

That's why you see practically no delay for local connections (low latency) and why queries run fast once the connection is established (no negotiation). There's no real fix, just make sure that once you get a connection you make the most of it and avoid making new connections unless absolutely necessary.

First, try to do the same thing with PDO like this php code :

echo microtime(true)."\n";
$con = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');    
echo microtime(true)."\n";    
$q = $con->query("select * from tablename where id='35'");    
echo microtime(true)."\n";

If the execution time is still the same, you will have to do a cache system to reduce the number of connections to the database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM