What are the steps PHP uses for long redis connections

Source: Internet
Author: User
Tags pconnect unix domain socket
This time for everyone to bring PHP use Redis long connection What steps, PHP use long-term connection of redis what to note, here is the actual case, take a look.

Php-redis Project on GitHub address: Https://github.com/phpredis/phpredis

pconnect function Declaration

Where time_out indicates how many seconds the client is idle and disconnects. The function connection returns true successfully, and the failure returns false:

Pconnect (host, Port, Time_out, persistent_id, Retry_interval)    host:string. Can is a host, or the path to a UNIX Domai N Socket    port:int, optional    timeout:float, value in seconds (optional, default is 0 meaning unlimited)    Persi Stent_id:string. Identity for the requested persistent connection    Retry_interval:int, value in milliseconds (optional)

The following example details the reuse of a pconnect connection.

$redis->pconnect (' 127.0.0.1 ', 6379); $redis->pconnect (' 127.0.0.1 '); The default port, 6379, uses the same connection as the example above. $redis->pconnect (' 127.0.0.1 ', 6379, 2.5); Set the expiration time of 2.5 seconds. will be different from the new connection above $redis->pconnect (' 127.0.0.1 ', 6379, 2.5, ' X '); Set the ID of the persistent connection, which will be different from the new connection above $redis->pconnect ('/tmp/redis.sock '); UNIX domain socket-would is another connection than the four before.

Pconnect Usage Introduction

A brief description of the Pconnect method

Using this method to create a connection, the connection is not closed after the Close method is called, and the connection is closed only after the process has finished.

[To be verified] If you are using a long connection, the timeout configuration entry in the Redis configuration file needs to be set to 0, otherwise the connection in the connection pool will expire due to a timeout

For PHP-FPM to explain Pconnect

Long connections end only after the PHP-FPM process ends, and the lifetime of the connection is the life cycle of the PHP-FPM process.
In the case of a shorter connection, a Redis connection is generated during each PHP-FPM call, and the table Form on the server is too much time_out connection state.
In contrast to long connections, all CGI PHP-FPM calls will only share a single long connection, so it will only produce a fixed number of time_out.

Close Long Connection

You can call the close and unset methods, but the two differ greatly:

-The function of close is simply to make the current PHP process no longer redis requests, but cannot really close the Redis long connection, the connection will still be reused in subsequent requests, and the straight FPM process life cycle ends. So close does not destroy the Redis object, just disconnects.

-The unset variable will not be destroyed. It is also important to note that you do not use Pconnect to close, and if the current script executes for a long time, it will always occupy a connection.

How to determine if the current Redis is in a connected state

The equivalent problem is that in singleton mode, the current instance is judged to be valid.

It is customary to call echo to determine whether the string itself is returned normally, or to call ping to see if the return value is +pong.

However, it is particularly careful to throw an exception when the Redis is called and the ping (return ' +POMG ') is invoked after it disconnects. So it's going to be handled by the exception capture mechanism.

Code Analysis Pconnect Connection Reuse issues

Case one: non-singleton mode.

Description: A connection was shared between A and B instances, and the B instance modified the connection to instance a:
So the following example causes the value of the final $ A instance to become 2, which requires special attention.

$a = pconnect (host, Port, Time_out), select (3), $a-Setex (ID, 3), Echo $a-get (ID), and//after performing the following connection $b = Pconnect (host, p ORT, Time_out), select (2), $b->set (id,2) echo $a->get (ID);  The DB of this ID operation becomes 2, no longer the previous 3. Because the two connections share a single connection channel.

Case two: a singleton pattern.

Modify the code above, both A and B are generated through getinstance. The premise of the build is to determine whether the current instance exists. The confusing point of the singleton pattern is:

$a generates an instance, when $b is generated, $b uses a $ A instance, and then modifies a $ A connection, then the call to $ A is definitely the instance after the $b modification. Consistent with the situation.
The code for the singleton pattern is as follows:

public static function getinstance ($db = 0) {  if (!isset (self::$_instance)) {    self::$_instance = new Redis ();  }  Self::_connect ();  Self::$_instance->select ($db);  return self::$_instance;}

Both cases illustrate the issue of connection reuse. How do I fix this bug? Two:

1. Generate a single case for each db.
2. Avoid connection reuse issues.

So the code can be adjusted to return a single-case array:

public static function getinstance ($db = 0) {  try{    if (isset (self::$_instance[$db]) && self::$_instance [$db]->ping () = = ' Pong ') {      return self::$_instance[$db];}  catch (Exception $e) {  } self  :: $_instance[$db] = new Redis ();  Self::_connect ($db);  return self::$_instance[$db];}

Places to be aware of

Avoid using Redis objects in the task class member variables.

In the Redis singleton mode, the expiration time of the time_out is declared. If the Redis process is a task, the task calls the Redis interval longer. When the interval is greater than time_out, Redis disconnects, and all operations to Redis are invalidated. The workaround is to avoid this invocation by dynamically declaring the Redis class where it is called. This problem is not differentiated for long connections and short links, and is called in the wrong way.

Believe that you have read the case of this article you have mastered the method, more exciting please pay attention to the PHP Chinese network other related articles!

Recommended reading:

Php+mysql achieve AD Click Statistics (with code)

PHP Chinese Tool class Chineseutil how to convert Chinese characters and pinyin

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.