我正在使用 PHP 创建一个进程来监控我们的数据库并在数据库出现故障时在我们的网站上放置一个维护页面。
我正在使用 PDO 和 Oracle。
我正在尝试使用一个数据库连接并每分钟查询一次,如果有问题会提醒人们。但是,如果数据库出现故障,脚本会等待 15 分钟,然后才发现有问题,所以我应该每分钟检查一次的进程最终看起来像这样:
06:56:46: SUCCESS -- I take down the database after this success
07:12:48: FAILURE - sent email
07:13:48: FAILURE
...
我想立即收到电子邮件,而不是 15 分钟后。有什么方法可以维护持久的数据库连接,还是每次准备和运行查询时都必须创建一个新连接?
如果有帮助,这里有一段代码:
$last_email_time = null; // the time of the last error email sent
$db_conn = null;
$script_start_time = time();
while(true) {
$success = false;
// attempt to create a database connection
if(!$db_conn) {
try {
$db_connection_data = $g_pdo_connection_data['freedom'];
$db_conn = new PDO($db_connection_data['string'], $db_connection_data['user'], $db_connection_data['password']);
$db_conn->setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db_conn->setAttribute (PDO::ATTR_TIMEOUT, 60);
if(!$db_conn) {
throw new Exception("Unable to create a database connection");
}
} catch(Exception $e) {
$last_email_time = handle_error($last_email_time, $e->getMessage());
$db_conn = null;
}
}
// attempt a query
if($db_conn) {
try {
$q = $db_conn->prepare("SELECT 1 FROM DUAL");
$q->execute();
$q->closeCursor();
if(!$q) {
throw new Exception("Unable to query the database");
}
$success = true;
} catch(Exception $e) {
$last_email_time = handle_error($last_email_time, $e->getMessage());
}
}
// remove the maintenance page if we were successful, else clear the connection
if($success) {
handle_success();
$last_email_time = null;
} else {
$db_conn = null;
}
flush();
if(ob_get_contents() != '') {
ob_flush();
}
sleep(60);
}