PDO connection pooling management

8

We often see in multithreaded applications that use a connection to a database, the use of a connection polling , in which it stores a pool of open connections. way to increase performance so that you do not have to open connections at all times or have to wait for another thread to finish an operation on the database.

I was seeing some connection implementations with the database using the PHP PDO and all are not concerned with connection pooling, and a PHP webserver is accessed simultaneously by hundreds, thousands of multithreaded in>).

What I see most is something similar to the code below, it is called the getConnection() method and in the method a new instance is created for the PDO class, that is, every HTTP request is created a new connection without necessity, and the use of connection pooling could be applied.

public function getConnection() {
    try {
        // realiza a conexão
        $this->con = new PDO($this->dbType.":host=".$this->host.";dbname=".$this->db, $this->user, $this->senha, 
        array( PDO::ATTR_PERSISTENT => $this->persistent ) );
        // realizado com sucesso, retorna conectado

        return $this->con;
    } catch ( PDOException $ex ){ //caso ocorra um erro, retorna o erro
        echo "Erro: ".$ex->getMessage(); 
    }     
}

Questions:

Does the PDO manage this pool of connections automatically?

Does each HTTP request create a connection to the database, made the transaction, and then closed?

Is not it possible to increase performance in PDO-PHP using a pool of connections? If there is anything of the sort, they could leave me links to study, I can not find complex material that addresses this well.

    
asked by anonymous 28.07.2014 / 19:21

1 answer

7

You do not need to manage this in PHP, because you use PDO::ATTR_PERSISTENT as true PDO / PHP will reuse the connections.

If you use Apache, and configured it to work with 80 threads , for example, you will see that in your database there will be 80 connections and if you follow the life of these connections, you will see that they will last as long as each webserver thread.

The optimization you are looking for is closely linked to the webserver configuration. Here comes experience and load testing.

    
28.07.2014 / 19:58