1.pconnect
/**
* Connects to a Redis instance or reuse a connection already established with pconnect/popen.
*
* The connection will not be closed on close or end of request until the php process ends.
* So be patient on to many open FD's (specially on redis server side) when using persistent connections on
* many servers connecting to one redis server.
*
* Also more than one persistent connection can be made identified by either host + port + timeout
* or host + persistent_id or unix socket + timeout.
*
* This feature is not available in threaded versions. pconnect and popen then working like their non persistent
* equivalents.
*
* @param string $host can be a host, or the path to a unix domain socket
* @param int $port optional
* @param float $timeout value in seconds (optional, default is 0 meaning unlimited)
* @param string $persistent_id identity for the requested persistent connection
* @return bool TRUE on success, FALSE on ertcnror.
*/
public function pconnect( $host, $port = 6379, $timeout = 0.0, $persistent_id = null ) {}
2.不带端口
<?php
namespace app\index\controller;
use Redis;
class Index
{
public function index()
{
$redis = new Redis();
$con = $redis->pconnect('127.0.0.1');
var_dump($con);//bool(true)
}
}
2.带端口
<?php
namespace app\index\controller;
use Redis;
class Index
{
public function index()
{
$redis = new Redis();
$con = $redis->pconnect('127.0.0.1',6379);
var_dump($con);//bool(true)
}
}
3.带超时
<?php
namespace app\index\controller;
use Redis;
class Index
{
public function index()
{
$redis = new Redis();
// 超过3秒放弃
$con = $redis->pconnect('127.0.0.1',6379,3);
var_dump($con);//bool(true)
}
}
4.x作为persistent_id发送,并且是之前的三个连接。
$redis->pconnect('127.0.0.1', 6379, 2.5, 'x');
5.nix域套接字 - 将是之前的四个连接。
$redis->pconnect('/tmp/redis.sock');
6.pconnect和connect区别
connect 脚本结束之后连接就释放了
pconnect 脚本结束之后连接不释放,保存在php-fpm进程中
connect在大量的php请求请求到redis的时候,这种方式会不断的建立和关闭连接,占用很多资源,导致服务器出现大量的TIMEW_WAIT,这样就会有很多php请求无法连接redis,出现Redis server went away
这个异常,实际就说明redis服务没有收到请求。
pconnect方法建立后的连接并不随这请求的结束而关闭,而是依赖于php-fpm
进程,php-fpm
进程不死,redis connect
就一直存在,直到空闲超时自动断开(目前redis timeout 600
),这样就极大的提高了redis connect
的重复利用,减少大量的IO
开销。不过这样也就出现一个瑕疵,就是redis的connect clients
数量要比以前高出很多