简体   繁体   English

Yii2 / PHP:检查与MySQL和PostgreSQL的连接

[英]Yii2/PHP: Check connection to MySQL and PostgreSQL

When starting my Yii2/PHP application, how can I check if / wait until the database is up? 启动我的Yii2 / PHP应用程序时,如何检查/等待数据库启动?

Currently with MySQL I use: 目前使用MySQL我使用:

$time = time();
$ok = false;
do {
  try {
    $pdo = new PDO($dsn,$username,$password);
    if ($pdo->query("SELECT 1 FROM INFORMATION_SCHEMA.SCHEMATA")) 
        $ok=true;
  } catch (\Exception $e) {
    sleep(1);
  }
} while (!$ok && time()<$time+30); 

Now I want make my application running with MySQL and PostgreSQL. 现在我想让我的应用程序与MySQL和PostgreSQL一起运行。

But SELECT 1 FROM INFORMATION_SCHEMA.SCHEMATA does not work in PostgreSQL. SELECT 1 FROM INFORMATION_SCHEMA.SCHEMATA在PostgreSQL中不起作用。

Is there a SQL-statement (using PDO database connectivity) that works on both database systems to check if the database is up and running? 是否有一个SQL语句(使用PDO数据库连接)可以在两个数据库系统上运行,以检查数据库是否已启动并正在运行?

Yii2 has a property to verify if a connection exists or not, it is really not necessary to create a script for this, since this framework has an abstraction implemented for the databases it supports ( $isActive property ). Yii2具有验证连接是否存在的属性,实际上没有必要为此创建脚本,因为该框架具有为其支持的数据库实现的抽象( $ isActive属性 )。

$isActive public read-only property Whether the DB connection is established $ isActive public read-only property是否建立了DB连接

public boolean getIsActive ( ) public boolean getIsActive()

You can do the check in your default controller in the following way: 您可以通过以下方式检查default controller

<?php

class DefaultController extends Controller 
{
    public function init()
    {
        if (!Yii::$app->db->isActive) {
            // The connection does not exist.
        }

        parent::init();
    }
}

It is not good practice to force waiting for a connection to a database unless there are very specific requirements. 除非有非常具体的要求,否则强制等待连接到数据库不是好的做法。 The availability of a connection to the database must be a mandatory requirement for an application to start and the application should not "wait" for the database to be available. 与数据库的连接的可用性必须是应用程序启动的强制要求,并且应用程序不应“等待”数据库可用。

There are ways to run containers in docker in an orderly manner or with a specific requirement, this link could give you a better option instead of delegating this to the application. 有些方法可以有序地或有特定的要求在docker中运行容器,这个链接可以为您提供更好的选择,而不是将其委托给应用程序。

You could use SELECT 1 which is standard SQL. 您可以使用标准SQL的SELECT 1

You can use dbfiddle to test against various servers. 您可以使用dbfiddle来测试各种服务器。

The server could go away an any time so checking the error response with every query is a much better approach. 服务器可以随时消失,因此检查每个查询的错误响应是一种更好的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM