【thinkphp5操作redis系列教程】pconnect(或popen)连接

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数量要比以前高出很多

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值