我需要用laravel应用程序动态连接许多数据库。
如何设置数据库连接池?
例如,有许多二级域名,如下所示:
chicago.example.com
newyork.example.com
losangeles.example.com
...它们有单独的数据库:
chicago
newyork
losangeles
...我像这样动态地连接这些数据库:
public function store(Request $request)
{
//post request from http://chicago.example.com/articles
$server_name_arr=explode('.',$_SERVER['SERVER_NAME']); //the result is ['chicago','example','com']
$db=array_slice($server_name_arr,-3,1)[0]; //the result is 'chicago'
Config::set('database.connections.mysql.database', $db);
DB::reconnect('mysql');
//...
}为了提高性能,我想设置数据库连接池,如何在laravel中实现?
发布于 2022-11-24 10:47:31
如果您有很多不同的代码实例,并且很难管理配置(env文件),您可以修改代码,添加一个条件来修改env文件,并在需要时缓存配置。如果您只需要一个管理功能,它将无法工作,如果您有一个实例,请查看下面的代码。
如果您有一个实例和一个DB服务器,那么也许您可以使用表前缀来区分您的表,我的意思是根据您的子域使用不同的前缀复制所有的表。
但是,如果您真的需要数据库协作池,那么在Github有一些类似于这的解决方案,但我从未尝试过。
public function store(Request $request)
{
//post request from http://chicago.example.com/articles
$server_name_arr=explode('.',$_SERVER['SERVER_NAME']); //the result is ['chicago','example','com']
$db=array_slice($server_name_arr,-3,1)[0]; //the result is 'chicago'
$current_db = DB::connection()->getDatabaseName();
if($db != $current_db){
$path = base_path('.env');
file_put_contents($path, str_replace('DB_DATABASE=' . current_db,
'DB_DATABASE=' . $db, file_get_contents($path)));
Artisan::call('config:cache');
}
//...
} https://stackoverflow.com/questions/50216525
复制相似问题