第一方案连接:
https://blog.csdn.net/mark885/article/details/137040284
思路:通过 Hyperf\Contract\ConfigInterface 配置接口类修改内存中的配置信息,在框架启动完成后的事件中定义监听(效果是框架启动后自动设置一次数据库连接池配置)。
1.App\System\Service\SystemConfig\ConfigDatabaseService.php 内容:
<?php
declare(strict_types=1);
namespace App\System\Service\SystemConfig;
use Mine\Abstracts\AbstractService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Contract\ConfigInterface;
class ConfigDatabaseService extends AbstractService
{
#[Inject]
protected ConfigInterface $config;
//获取进程中 数据库连接池 数组
public function getDatabasePool(): array
{
return $this->config->get('databases', []);
}
//重新设置进程中 数据库连接池 数组
public function setDatabasePool(): void
{
$dbDefault = $this->getDatabasePool();
//$dbList 数据库id,最终组成的数据库是:newdb_1, newdb_2
$dbList = [['id' => 1], ['id' => 2], ['id' => 3]];
$dbArr = [];
foreach ($dbList as $key => &$val){
$val = (array)$val;
if(isset($dbDefault['newdb_' . $val['id']])){
continue;
}
$tmp = $dbDefault['default'];
//数据库名
$tmp['database'] = 'newdb_' . $val['id'];
//还可以修改host 密码等,自己打印 $dbDefault 出来看
//缓存名
$tmp['cache']['cache_key'] = 'DbCache:'.$val['id'].':%s:m:%s:%s:%s';
$dbArr['newdb_' . $val['id']] = $tmp;
unset($tmp);
}
if(count($dbArr)){
$this->config->set('databases', array_merge($dbDefault, $dbArr));
}
}
}
2. App\System\Listener\ConfigDbListener.php 内容:
<?php
declare(strict_types=1);
namespace App\System\Listener;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use Hyperf\Framework\Event\AfterWorkerStart;
use App\System\Service\SystemConfig\ConfigDatabaseService;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
/**
* Class ConfigDbListener.
*/
#[Listener]
class ConfigDbListener implements ListenerInterface
{
public function listen(): array
{
return [
AfterWorkerStart::class,
];
}
/**
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function process(object $event): void
{
try {
//框架启动后,重新设置数据库连接池
$configDatabaseService = container()->get(ConfigDatabaseService::class);
$configDatabaseService->setDatabasePool();
unset($configDatabaseService);
} catch (\Exception $e) {
}
}
}
3.手动设置:
$configDatabaseService = container()->get(ConfigDatabaseService::class);
$configDatabaseService->setDatabasePool();
4.在任意控制器中获取数据库配置是否成功:
$configDatabaseService = container()->get(ConfigDatabaseService::class);
$res = $configDatabaseService->getDatabasePool();
var_dump($res);
以上就是在hyperf中动态设置数据库连接池,觉得对您有帮助的话呢,赞赞赞一下。
场景示例:
前端用户注册成功立即为用户创建一个新数据库,用户5秒内登录,不重启hyperf框架,实现登录后即可连接刚刚创建的新数据库。
//注册验证代码省略一万行
\Hyperf\Coroutine\go(function () use ($clinicId){
//1.为用户创建一个数据库
//2.重新设置数据库连接池
$configDatabaseService = container()->get(ConfigDatabaseService::class);
$res = $configDatabaseService->getDatabasePool();
unset($configDatabaseService);
});
//响应前端、注册成功了,可以立即登录