Stałe połączenia z bazami danych

Stałe połączenia (persistent connections) to połączenia, które nie są zamykane po wykonaniu skryptu. Kiedy skrypt próbuje nawiązać stałe połączenie, PHP sprawdza czy istnieje już identyczne połączenie (otwarte wcześniej) i jeśli istnieje, używa go. Jeżeli nie, tworzone jest nowe. Połączenie 'identyczne' to połączenie z tym samym hostem, z taką samą nazwą użytkownika i hasłem.

Ludzie niezbyt dobrze znający zasady działania serwerów mogą czasem brać stałe połączenia za coś, czym te nie są. Stałe połączenia nie stwarzają możliwości otwarcia połączenia dla konkretnego użytkonika, nie pozwalają na skuteczne stworzenie systemu transakcji, i nie robią wielu innych rzeczy. Powiedzmy to jasno, stałe połączenia nie oferują nic ponad to, co robią 'zwykłe' połączenia.

Dlaczego?

Jest to związane z zasadą działania serwerów. Są trzy sposoby na które serwer może wykorzystac PHP do generowania stron.

Pierwsza metoda to wykorzystanie PHP jako "wrappera" CGI. Przy wywołaniu skryptu każdorazowo uruchamiany i niszczony jest egzamplarz PHP. Jako, że jest on niszczony po każdym wywołaniu, wszystkie zasoby przez niego posiadane (na przykład połączenia z bazą danych) są tracone. W tym przypadku używanie stałych połączeń nie przynosi korzyści, one po prostu nie są stałe.

Druga, najpopularniejsza metoda, to uruchomienie PHP jako modułu w wieloprocesowym serwerze, co obecnie dotyczy jedynie serwera Apache. Serwer wieloprocesowy zwykle uruchamia jeden proces (rodzica), który koordynuje inne procesy (potomne) zajmujące się dostarczaniem stron. Kiedy nadchodzi żądanie od klienta, jest ono przekazywane jednemu z procesów potomnych, który w danym momencie nie obsługuje innego klienta. Oznacza to, że gdy ten sam klient wyśle do serwera kolejne żądanie, może zostać obsłużony przez inny proces niż za pierwszym razem. Stałe połączenie w tym przypadku oznacza, że każdy proces potomny ustanawia połączenie z serwerem SQL przy pierwszym wywołaniu strony, która takiego połączenia używa.

Ostatnia metoda to wykorzystanie PHP jako wtyczki (plug-in) do serwera wielowątkowego. Obecnie PHP4 zawiera obsługę mechanizmów ISAPI, WSAPI i NSAPI (w Windows), które umożliwiają uruchomienie PHP jako wtyczki do wielowątkowych serwerów takich jak Netscape FastTrack (iPlanet), Microsoft Internet Information Server (IIS) i O'Reilly WebSite Pro. Zachowanie PHP jest zasadniczo takie samo jak w przypadku opisanego wcześniej modelu wieloprocesowego.

Skoro stałe połączenia nie dostarczają większej funkcjonalności, do czego mogą być przydatne?

Odpowiedź jest niezwykle prosta -- wydajność. Stałe połączenia sprawdzają się w przypadku, gdy koszt nawiązania połączenia z SQL serwerem jest wysoki. To czy koszt jest duży czy nie zależy od wielu czynników. Na przykład od typu bazy danych, od tego czy znajduje się ona na tym samym serwerze, od obciążenia maszyny, która obsługuje serwer SQL, itd. Jeśli zatem koszt połączenia jest wysoki, stałe połączenia znacznie pomagają. Sprawiają, że proces potomny łączy się z serwerem SQL tylko raz podczas swojego życia, zamiast otwierać połączenie za każdym razem gdy zażąda tego skrypt. Oznacza to, że każdy proces potomny, który nawiązał stałe połączenie, będzie posiadał własne połączenie z serwerem bazy danych. Dla przykładu, jeżeli 20 procesów potomnych uruchomi skrypt, który ustanowi stałe połączenie z serwerem SQL, będziesz mieć 20 różnych połączeń z serwerem, jedno na każdy proces.

Trzeba jednak zauważyć, że może to mieć swoje ujemne strony w przypadku, gdy limit połączeń do bazy danych zostanie przekroczony przez stałe połączenia z procesów potomnych. Jeśli twoja baza danych posiada limit szesnastu jednoczesnych połączeń, a w danej chwili obciążenie jest wysokie, siedemnasty proces nie będzie mógł się połączyć. Jeśli twoje skrypty zawierają błędy, które nie pozwalają zamknąć połączeń (na przykłąd nieskończone pętle), baza danych z limitem 16 połączeń może szybko zostać zapchana. Poszukaj w dokumentacji swojej bazy danych w jaki sposób radzi sobie ona z porzuconymi lub bezczynnymi połączeniami.

Ostrzeżenie

Istnieje kilka zagrożeń, które należy brać pod uwagę decydując się na używanie stałych połączeń. Jednym z nich jest sytuacja, w której skrypt blokujący tabelę, z jakiegokolwiek powodu nie może zdjąć blokady. Wtedy kolejne skrypty korzystające z tego samego połączenia będą zablokowane i może zajść potrzeba ponownego uruchomienia serwera httpd lub serwera bazy danych. Kolejne zagrożenie dotyczy transakcji. Jeśli skrypt używający transakcji zakończy działanie przed zakończeniem bloku transakcji, to zostanie on (blok) przeniesiony do następnego skryptu. W obu przypadkach można użyć register_shutdown_function(), aby zarejestrować funkcję porządkującą, która odblokuje tabele lub wycofa transakcje. Najlepiej jednak jest zrezygnować ze stałych połączeń w skryptach używających blokowania tabel lub transakcji.

Istotne podsumowanie. Stałe połączenia zostały zaprojektowane tak, by odpowiadać zwykłym połączeniom. Oznacza to, że zawsze możesz zastąpić stałe połączenia zwykłymi i nie zmieni to zachowania skryptu. Natomiast może zmienić (i zapewne zmieni) jego wydajność!

Zobacz także fbsql_pconnect(), ibase_pconnect(), ifx_pconnect(), ingres_pconnect(), msql_pconnect(), mssql_pconnect(), mysql_pconnect(), ociplogon(), odbc_pconnect(), oci_pconnect(), pfsockopen(), pg_pconnect() i sybase_pconnect().

add a note add a note

User Contributed Notes 13 notes

up
16
php at alfadog dot net
10 years ago
One additional not regarding odbc_pconnect  and possibly other variations of pconnect:

If the connection encounters an error (bad SQL, incorrect request, etc), that error will return with  be present in odbc_errormsg for every subsequent action on that connection, even if subsequent actions don't cause another error.

For example:

A script connects with odbc_pconnect.
The connection is created on it's first use.
The script calls a query "Select * FROM Table1".
Table1 doesn't exist and odbc_errormsg contains that error.

Later(days, perhaps), a different script is called using the same parameters to odbc_pconnect.
The connection already exists, to it is reused.
The script calls a query "Select * FROM Table0".
The query runs fine, but odbc_errormsg still returns the error about Table1 not existing.

I'm not seeing a way to clear that error using odbc_ functions, so keep your eyes open for this gotcha or use odbc_connect instead.
up
6
ynzhang from lakeheadu canada
15 years ago
It seems that using pg_pconnect() will not persist the temporary views/tables. So if you are trying to create temporary views/tables with the query results and then access them with the next script of the same session, you are out of luck. Those temporary view/tables are gone after each PHP script ended. One way to get around this problem is to create real view/table with session ID as part of the name and record the name&creation time in a common table. Have a garbage collection script to drop the view/table who's session is expired.
up
3
christopher dot jones at oracle dot com
16 years ago
For the oci8 extension it is not true that " [...] when using transactions, a transaction block will also carry over to the next script which uses that connection if script execution ends before the transaction block does.".  The oci8 extension does a rollback at the end scripts using persistent connections, thus ending the transaction.  The rollback also releases locks. However any ALTER SESSION command (e.g. changing the date format) on a persistent connection will be retained over to the next script.
up
1
Tom
14 years ago
There's a third case for PHP: run on a fastCGI interface. In this case, PHP processes are NOT destroyed after each request, and so persistent connections do persist. Set PHP_FCGI_CHILDREN << mysql's max_connections and you'll be fine.
up
0
ambrish at php dot net
13 years ago
In IBM_DB2 extension v1.9.0 or later performs a transaction rollback on persistent connections at the end of a request, thus ending the transaction. This prevents the transaction block from carrying over to the next request which uses that connection if script execution ends before the transaction block does.
up
-2
pacerier at gmail dot com
8 years ago
Did anyone else notice that the last paragraph contradicts everything above it?

( cached page: https://archive.is/ZAOwy )
up
-1
andy at paradigm-reborn dot com
17 years ago
To those using MySQL and finding a lot of leftover sleeping processes, take a look at MySQL's wait_timeout directive. By default it is set to 8 hours, but almost any decent production server will have been lowered to the 60 second range. Even on my testing server, I was having problems with too many connections from leftover persistent connections.
up
-7
fabio
18 years ago
You can in fact provide a port for the connection, take a look at http://de2.php.net/manual/en/function.mysql-pconnect.php#AEN101879

Just use "hostname:port" for the server address.
up
-10
RQuadling at GMail dot com
18 years ago
If you have multiple databases on the same server AND you are using persistent connections, you MUST prefix all the table names with the specific database name.

Changing the database using the xxx_select_db functions alters the database for the connection for all users who are sharing that connection (assuming PHP is running shared and not CGI/CLI).

If you have 2 databases (live and archive) and your script is talking to both, you cannot use 2 persistent connections and change the database for each one.

Internally, persistent connections are used even if you do not specify that you want to use persistent connections. This is why new_link was added to mysql_connect/mssql_connect (PHPV4.2.0+).
up
-11
whatspaz at g NO dot SPAM mail dot c o m
17 years ago
in response to web at nick, have you tried FLUSH PRIVILEGES. this should reload those privileges.
up
-13
jean_christian at myrealbox dot com
21 years ago
If anyone ever wonders why the number of idle db process (open connections) seems to grow even though you are using persistent connections, here's why:

"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."
up
-22
aaryal at foresightint dot com
20 years ago
this one bit quite a bit of chunk out of my you-know-what. seems like if you're running multiple database servers on the same host (for eg. MySQL on a number of ports) you can't use pconnect since the port number isn't part of the key for database connections. especially if you have the same username and password to connect to all the database servers running on different ports. but then it might be php-MySQL specific. you might get a connection for an entirely different port than the one you asked for.
up
-33
jorgeleon85 at gmail dot com
13 years ago
I've been looking everywhere for a benchmark or at least comparison of the overhead used by oci_connect and oci_pconnect.
Just saying "oci_connect is slower because the overhead..." is not enough for me. For than I wrote a couple scripts to compare perfomance.
At the end I found out an average of 34% more time using a oci_connect than oci_pconnect, using a query of 50 rows and 100 columns.
Obviously this wasn't a real benchmark however it gives a simple idea of the efficiency of each function.
To Top