gpt4 book ai didi

doctrine-orm - Doctrine 2 主/从连接

转载 作者:行者123 更新时间:2023-12-04 05:23:46 25 4
gpt4 key购买 nike

我正在研究设置 Doctrine 2 以使用 MySQL 的主/从连接的不同方法。设置将是一个主数据库和多个从属数据库。所有 SELECT 语句都应该来自一个随机的事件从属,并且任何 UPDATE、INSERT、DELETE 语句都将始终委托(delegate)给主连接。

有没有人以这种方式设置 Doctine 2 或对如何处理它有任何想法?

最佳答案

Doctrine2 现在在\Doctrine\DBAL\Connections 命名空间中有一个 MasterSlaveConnection。

编辑:
除非这篇文章不起作用,否则不要阅读下面的内容

不再需要重载程序,dbal 配置将自行获取从站。例如

connections:
default:
driver: %database_driver%
host: %database_host%
dbname: %database_name%
user: %database_user%
password: %database_password%
slaves:
slave1:
host: %database_slave1%
dbname: %database_name%
user: %database_user%
password: %database_password%

如果上述方法不起作用,试试这个

一些简单的事情,只需在每个主机之间放置管道(|)
default:
driver: %database_driver%
host: %database_host%|%database_slave%|%database_slave2%
port: 3306
dbname: %database_name%
user: %database_user%
password: %database_password%
wrapper_class: \Foo\Bar\Symfony\Doctrine\Connections\MasterSlave


<?php
namespace Foo\Bar\Symfony\Doctrine\Connections;
use \Doctrine\DBAL\Connections\MasterSlaveConnection;
use Doctrine\DBAL\Connection,
Doctrine\DBAL\Driver,
Doctrine\DBAL\Configuration,
Doctrine\Common\EventManager,
Doctrine\DBAL\Event\ConnectionEventArgs,
Doctrine\DBAL\Events,
Doctrine\DBAL\Cache\QueryCacheProfile;

class MasterSlave extends MasterSlaveConnection
{
public function __construct(array $params, Driver $driver, Configuration $config = null, EventManager $eventManager = null)
{
$tempParams = array(
'master' => array()
, 'slaves' => array()
, 'driver' => $params['driver']
);
$hosts = explode('|', $params['host']);
unset($params['host']);
foreach($hosts as $num => $host)
{
$params['host'] = $host;
if($num == 0)
{
$tempParams['master'] = $params;
}
else
{
$tempParams['slaves'][] = $params;
}
}

if(!isset($tempParams['master']['driver']))
$tempParams['master']['driver'] = "pdo_mysql";

foreach($tempParams['slaves'] as $k => $slave)
{
if(!isset($slave['driver']))
$tempParams['slaves'][$k]['driver'] = "pdo_mysql";
}
parent::__construct($tempParams, $driver, $config, $eventManager);
}

public function executeQuery($query, array $params = array(), $types = array(), QueryCacheProfile $qcp = null)
{
try
{
return parent::executeQuery($query, $params, $types, $qcp);
}
catch(\Exception $e)
{
$logger = new \Uelib\Core\Logger();
$message = $e->getMessage() . "\nSql: " . $query . "\nParams: \n" . print_r($params, true);
$logger->log($message);
throw $e;
}
}
}

关于doctrine-orm - Doctrine 2 主/从连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4922723/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com