【发布时间】:2016-11-23 04:25:52
【问题描述】:
我将Laravel 5 与php 5.5.9-1ubuntu4.14 和mysql 5.5.47 一起使用。
我有一个多租户环境,每个租户都有一个单独的数据库。因此,对于每个 HTTP 请求,我都会在 BeforeMiddleware 中设置适当的数据库连接,就像这样
public function handle($request, Closure $next)
{
...
// Set the client DB name and fire it up as the new default DB connection
Config::set('database.connections.mysql_client.host', $db_host);
Config::set('database.connections.mysql_client.database', $db_database);
Config::set('database.connections.mysql_client.username', $db_username);
Config::set('database.connections.mysql_client.password', $db_password);
DB::setDefaultConnection('mysql_client');
...
}
即使对于并发 HTTP 请求,这也能正常工作。
但现在我想将计划作业添加到我的应用程序中。这些作业将向属于所有租户的用户发送通知。所以,我再次需要连接到各自的租户数据库。但此连接不会通过 HTTP 请求。假设我有一个 CommunicationController 和一个用于发送通知的函数。
public function sendNotification()
{
...
DB::purge('mysql_client');//IMP
// Set the client DB name and fire it up as the new default DB connection
Config::set('database.connections.mysql_client.host', $db_host);
Config::set('database.connections.mysql_client.database', $db_database);
Config::set('database.connections.mysql_client.username', $db_username);
Config::set('database.connections.mysql_client.password', $db_password);
DB::setDefaultConnection('mysql_client');
...
}
这是我设置Config 值的地方。该函数将通过Laravel Scheduler每分钟执行一次。
我的问题是:
- HTTP 请求进来时会发生什么?会不会有
在 HTTP 请求和计划作业中都设置了
Config参数的并发问题? - 如果 HTTP 请求与计划作业同时运行,它是否会连接到某些不正确的数据库?
【问题讨论】:
标签: php mysql laravel laravel-5