hyperf 多数据库(要分库的来看)实时连接第二方案(无需预先定义config连接池,无需重启项目)

本文介绍了如何在Hyperf框架中通过ConfigInterface配置接口修改内存中的数据库连接池配置,并在框架启动后自动设置。使用ConfigDatabaseService服务和ConfigDbListener监听器实现在用户注册成功后立即创建并切换数据库连接,无需重启框架。
摘要由CSDN通过智能技术生成

第一方案连接:

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);
});
//响应前端、注册成功了,可以立即登录
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Web项目开发

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值