PHP使PDO ATTR_PERSISTENT连接保持活动状态 [英] PHP Keeping a PDO ATTR_PERSISTENT connection alive

查看:593
本文介绍了PHP使PDO ATTR_PERSISTENT连接保持活动状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PDO持久连接运行无尽的PHP脚本,如下所示:

I am running an endless PHP Script with PDO Persistent Connection like this:

$conn=new PDO(
  'mysql:host=127.0.0.1','user','pass', array(PDO::ATTR_PERSISTENT => true)
);

mySQL wait_timeout变量设置为28800,出于测试目的,我将脚本闲置了12个小时.并自动断开连接,因此我假定PDO::ATTR_PERSISTENT属性被系统变量wait_timeout取代.

The mySQL wait_timeout variable is set to 28800 and I left the script on idle for 12 hours for test purposes; and the connection is dropped automatically so I presume the PDO::ATTR_PERSISTENT attribute is superseded by the system variable wait_timeout.

所以我想知道是否存在一种设置或另一种PHP方法来使连接保持呼吸,只要PHP脚本正在运行,那是否是一个好习惯.

So I was wondering whether theres a setting or another PHP method to keep the connection breathing as long as the PHP script is running and whether or not that would be a good practice.

我的计划B将每60分钟执行一次无资源的mySQL查询以重置时钟.

My plan B would be executing a resource-less mySQL query every 60 minutes to reset the clock.

操作系统:4GB RAM VPS Debian 64位SSD

推荐答案

我建议您使用另一种方法来处理这种情况.每当您需要在持久脚本中运行查询时,请确保存在连接.否则,请重新连接.

I would suggest you another way to handle such situations. Whenever you need to run a query in your long-lasting script ensure that there is a connnection. Otherwise reconnect.

    try {
        echo "Testing connection...\n";
        $old_errlevel = error_reporting(0);
        self::$pdo->query("SELECT 1");
    } catch (PDOException $e) {
        echo "Connection failed, reinitializing...\n";
        self::init();
    }

您可以在此处找到完整的类示例. 我还建议您在知道长时间不使用它时,在脚本中显式关闭该连接.

You can find the full class example here. I also suggest you to explicitly close the connection in your script when you know you will not use it for a long period.

这篇关于PHP使PDO ATTR_PERSISTENT连接保持活动状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆