折雨的天空

新浪微薄腾讯微薄

最新碎语:最近霉到了住。哎。。。

您的位置:折雨的天空 >php开发> 通过缓存日期,判断数据库连接是否超时

通过缓存日期,判断数据库连接是否超时

只是一种思路,解决出现:ora-02396的问题

出现问题的场景,从数据库查询出一万条记录,循环处理这一万条记录,处理完毕后,再继续查询,使用同一个连接或者连接池,这时候会提示连接超出最大空闲时间。


public static function getInstance($host=0){
        $databaseConfig=self::$databaseConfig;
        //设置超时时间
        $cache=new Cache(["host" => 'localhost',"port" => 6379,"password"=>'']);
        if(isset($databaseConfig[$host]) && is_array($databaseConfig[$host]) && !empty($databaseConfig))
        {
            if($cache->isExpire('db-connect-expire-time') || !isset(self::$instance[$host]))
            {
                if($databaseConfig[$host]['engine']=='oracle'){
                    try
                    {
                        self::$instance[$host] = new PDO('oci:dbname=//'.$databaseConfig[$host]['host'].';charset='.$databaseConfig[$host]['charset'],$databaseConfig[$host]['user'],$databaseConfig[$host]['password']);
                        $cache->set('db-connect-expire-time',180,180);
                    }
                    catch (PDOException $e)
                    {
                        throw new Exception($e,'500');
                    }
                }
                if($databaseConfig[$host]['engine']=='mysql'){
                    try
                    {
                        self::$instance[$host] = new PDO('mysql:dbname='.$databaseConfig[$host]['database'].';host='.$databaseConfig[$host]['host'].';charset='.$databaseConfig[$host]['charset'],$databaseConfig[$host]['user'],$databaseConfig[$host]['password']);
                        $cache->set('db-connect-expire-time',180,180);
                    }
                    catch (PDOException $e)
                    {
                        throw new Exception($e,'500');
                    }
                }
            }
        }
        else
        {
            throw new Exception('还未配置数据库服务器【'.$host.'】的信息,请先配置信息后重试!','500');
        }
        return self::$instance[$host];
    }

此方法局限性明显,不是最优,只是一种思路。

------------正 文 已 结 束, 感 谢 您 的 阅 读 (折雨的天空)--------------------

转载请注明本文标题和链接:《通过缓存日期,判断数据库连接是否超时

奖励一下

取消

分享不易,烦请有多多打赏,如您也困难,点击右边关闭即可!

扫码支持
扫码打赏,5元,10元,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

-秒后自动关闭,如已打赏,或者不愿打赏,请点击右上角关闭图标。

发表评论

路人甲 表情
看不清楚?点图切换