PHP uses Redis persistent connection methods, phpredis connection details

Source: Internet
Author: User
Tags pconnect unix domain socket

PHP uses Redis persistent connection methods, phpredis connection details

This article describes how PHP uses Redis persistent connection. We will share this with you for your reference. The details are as follows:

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

Pconnect function declaration

Time_out indicates the number of seconds after the client is idle. If the function is successfully connected, true is returned. If the function fails, false is returned:

pconnect(host, port, time_out, persistent_id, retry_interval)    host: string. can be a host, or the path to a unix domain socket    port: int, optional    timeout: float, value in seconds (optional, default is 0 meaning unlimited)    persistent_id: string. identity for the requested persistent connection    retry_interval: int, value in milliseconds (optional)

The following example details the reuse of pconnect connections.

$ Redis-> pconnect ('2017. 0.0.1 ', 6379); $ redis-> pconnect ('2017. 0.0.1 '); // default port 6379. The connection is the same as in the preceding example. $ Redis-> pconnect ('127. 0.0.1 ', 127, 6379); // set the expiration time of 2.5 seconds. It will be different from the above new connection $ redis-> pconnect ('2017. 0.0.1 ', 6379, 2.5, 'x'); // sets the id of the persistent connection, it will be different from the new connection $ redis-> pconnect ('/tmp/redis. sock '); // unix domain socket-wocould be another connection than the four before.

Pconnect usage

Brief description of the pconnect Method

If you use this method to create a connection, the connection will not be closed after the close method is called. The connection will be closed only after the process ends.

[To be verified] If persistent connections are used, set the timeout configuration item in the Redis configuration file to 0. Otherwise, the connection in the connection pool will fail due to timeout.

For PHP-FPM, A pconnect

Persistent connections only end after the PHP-FPM process ends, and the life cycle of the connection is the life cycle of the PHP-FPM process.
Compared with short connections, each PHP-FPM call process will produce a redis connection, the table form on the server is too many time_out connection status.
On the contrary, all CGI called by the PHP-FPM will share only one persistent connection, so that only a fixed number of time_out will be generated.

Disable persistent connection

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

-Close is only used to prevent the current PHP process from making redis requests, but cannot actually close the redis persistent connection. The connection will still be reused in subsequent requests and the live FPM process ends. Therefore, close does not destroy the redis object, but only disconnects.

-Unset variables will be destroyed. Note that you do not need to close the connection when pconnect is used. If the script is executed for a long time, it will still occupy a connection.

How to determine whether Redis is connected

The equivalent problem is that in singleton mode, you can determine whether the current instance is valid.

Traditionally, echo is called to determine whether the string itself is returned normally, or ping is called to check whether the returned value is + PONG.

However, it is important to note that an exception will be thrown when echo and ping (return '+ POMG') are called after redis is disconnected. Therefore, it is necessary to use the exception capture mechanism.

Code Analysis on pconnect connection Reuse

Case 1: Non-singleton mode.

Note: instance a and instance B share a connection. instance B modifies the connection of instance:
Therefore, the following example changes the final value of $ a to 2. Pay special attention to this.

$ A = pconnect (host, port, time_out); select (3); $ a-> setex (id, 3); echo $ a-> get (id ); // then run the following connection $ B = pconnect (host, port, time_out); select (2); $ B-> set (id, 2) echo $ a-> get (id); // The db for this id operation is changed to 2, not the previous 3. Because these two connections share a connection channel.

Case 2: Singleton mode.

Modify the code above. both a and B are generated by getInstance. The premise is to determine whether the current instance exists. The confusion of Singleton mode is:

$ A generates an instance. $ B is generated at this time. $ B uses the $ a instance and modifies the connection of $, after $ a is called, it must be the modified instance of $ B. This is the same as case 2.
The code for Singleton mode 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 indicate connection reuse. How to fix this bug? Two points:

1. Generate a singleton for each database.
2. Avoid connection reuse.

So the code can be adjusted to return a singleton 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];}

Notes

Avoid using redis objects in Task member variables.

In redis Singleton mode, the expiration time of time_out is declared. If redis is processing a task, and the task calls redis for a long time. When the interval is greater than time_out, redis will be disconnected. At this time, all operations on redis will fail. The solution is to avoid this call method by dynamically declaring the redis class at the place of the call. This problem is not distinguished between persistent connections and short connections, and is a call method error.

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.