简体   繁体   中英

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

I have a laravel project with many connections to different IP's.

I want laravel to connect to a backup database in the case that the main SQL server was down

Example.

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

If 192.168.1.2 goes down, laravel must connect to 192.168.1.3

I'd like to do this in database.php file, but I think that's impossible.

I was trying to test connection before make a query like this:

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

but it seems that it save data in cache and it still throw database name even if I shutdown the SQL server

For this answer, I'm considering Laravel 5.

By debugging a model query, I've found out that Laravel connections support not a single host, but a list of them.

[
    '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' => [],
]

The underlying method behind Laravel connections resolving is Illuminate\\Database\\Connectors::createPdoResolverWithHosts which has the following behavior:

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;
    };
}

Such behavior means that Laravel will randomly pick one of the connection's hosts and try to connect to them. If the attempt fails, it keeps trying until no more hosts are found.

You could define two mysql connections in app/config/database.php and using a middleware you could define the db that should be connected to.

You can find a more elaborate explanation in this URL:
http://fideloper.com/laravel-multiple-database-connections

i recently started searching for the same thing and to change the connection as soon as possible you can either

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
}

also check laravel api docs for more info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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