azi
azi

Reputation: 929

Persistent DB Connections aren't Getting Reused

I am using phpgacl library in one of my applications for authorization. This library is making connections to the database using mysql_pconnect. The problem is that the connections aren't getting reused and at times the whole application crashes down with error too many connections. I don't have too many concurrent users and hence increasing the max no of connections in mysql won't solve the problem permanently. I did a simple test to simplify the problem. I wrote a simple php script /var/www/a.php:

<?
mysql_pconnect('localhost', 'root', 'root');
?>

When I hit localhost/a.php for the first time, I see one connection to the database in mysql processlist. When I hit the link for the second time, I expect that connection to be reused. But, that's not the case. A new connection gets created and I see two connection in sleep state. The count increases every time I hit the link.

All these connections get closed when I restart apache.

I want to know how php mysql_pconnect works and how it uses previously made mysql connection. And, why is this not happening in the example I mentioned above?

One of the comments here reads:

You are probably using a multi-process web server such as Apache. Since database connections cannot be shared among different processes a new one is created if the request happen to come to a different web server child process.

Does this mean using mysql_pconnect with apache is not recommended?

Upvotes: 0

Views: 551

Answers (1)

kryoz
kryoz

Reputation: 87

Every DB connection dies with the end of php process. So it's expected that persistent connections won't share with other web threads. mysql_pconnect can share DB connection only for application run time among different classes i.e. The solutions to your problem are:

  1. reduce timeouts for DB connections in MySQL config
  2. close DB connections in your app
  3. make own daemon for DB queries (but it's very complicated)

Upvotes: 0

Related Questions