当主连接断开时,如何在laravel中设置第二个数据库


How to set second database in laravel when main connection is down

我有一个与不同IP的许多连接的laravel项目。

我想让laravel在主SQL服务器宕机的情况下连接到备份数据库

的例子。

192.168.1.2 -> SQL DB #1
192.168.1.3 -> SQL DB #1 Backup

如果192.168.1.2 down, laravel必须连接到192.168.1.3

我想在database.php文件中这样做,但我认为这是不可能的。

我试图测试连接之前做这样的查询:

if(DB::connection('connection')->getDatabaseName())

,但似乎数据保存在缓存中,它仍然抛出数据库名称,即使我关闭SQL服务器

对于这个答案,我考虑使用Laravel 5。

通过调试一个模型查询,我发现Laravel连接不支持单个主机,而是一个列表。

[
    'driver' => 'sqlsrv',
    'host' => [
        '192.168.1.2',
        '192.168.1.3',
    ],
    'database' => 'database_name',
    'username' => 'username',
    'password' => 'password',
    'charset' => 'utf8',
    'prefix' => '',
    'prefix_indexes' => true,
    'transaction_isolation' => PDO::SQLSRV_TXN_READ_UNCOMMITTED, // Not required, but worth mentioning it's possible to define it here too
    'options' => [],
]

Laravel连接解析背后的底层方法是Illuminate'Database'Connectors::createPdoResolverWithHosts,它具有以下行为:

protected function createPdoResolverWithHosts(array $config)
{
    return function () use ($config) {
        foreach (Arr::shuffle($hosts = $this->parseHosts($config)) as $key => $host) {
            $config['host'] = $host;
            try {
                return $this->createConnector($config)->connect($config);
            } catch (PDOException $e) {
                continue;
            }
        }
        throw $e;
    };
}

这样的行为意味着Laravel将随机选择一个连接的主机并尝试连接到它们。如果尝试失败,它会继续尝试,直到没有找到更多的主机。

你可以在app/config/database.php中定义两个mysql连接使用中间件,您可以定义应该连接到的数据库。

你可以在这个URL中找到更详细的解释:
http://fideloper.com/laravel-multiple-database-connections

我最近开始搜索相同的东西,并尽快更改连接,您可以

  • 在服务提供商中添加检查
  • 或通过全局中间件
try{
    'DB::connection()->getPdo();                 // check if we have a connection
}catch{
    'DB::purge(config('database.default'));      // disconnect from the current
    'DB::setDefaultConnection('my-fallback-db'); // connect to a new one
}