lin*_*san 5 php mysql laravel laravel-5
我使用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');
...
}
Run Code Online (Sandbox Code Playgroud)
即使对于并发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');
...
}
Run Code Online (Sandbox Code Playgroud)
这是我设置Config值的地方.此功能将每分钟执行一次Laravel Scheduler.
我的问题是:
Config在HTTP请求和预定作业中都设置了参数?查看Illuminate\Config\Repository用于外观的实现Config,特别是set方法
public function set($key, $value = null)
{
if (is_array($key)) {
foreach ($key as $innerKey => $innerValue) {
Arr::set($this->items, $innerKey, $innerValue);
}
} else {
Arr::set($this->items, $key, $value);
}
}
Run Code Online (Sandbox Code Playgroud)
您可以放心,该集不是 IO 集(即文件系统),而是内存中集。因此,每分钟运行的 CLI 调度程序命令将像其他每个 http 请求一样在其自己的上下文中运行。