2011-01-26 52 views
0

我有一个普遍的好奇心问题。在基于读写的服务器集上构建Web应用程序集

假设我有1个主服务器(用于写入)和5个从服务器(用于读取)。

在我的web应用程序中,我是否会启动一个连接主站和从站的连接?使用主连接仅用于发送写入并仅使用从属连接来读取数据?

回答

1

在任何情况下,您都应该根据需要处理主从连接,通常通过getConnection()函数处理。在我的设置工作,2群,硕士2名,上一个,8对其他的4个奴隶,功能基本上是这样的:

$query = "SELECT * FROM table"; 
$res = mysql_query($query, Custom_Db_Handler::get()->getConnection("my_db", Custom_Db_Handler::READ)); 

<?php 
class Custom_Db_Handler 
{ 
    const READ = "read"; 
    const WRITE = "write"; 

    private static $_instance; 

    private $_connections = array(); 
    private $_config; 

    private function __construct() { 
     $this->_config = Storage::get("config mysql"); 
    } 

    public function get() { 
     if(is_null(self::$_instance)) { 
      self::$_instance = new self; 
     } 
     return self::$_instance; 
    } 

    public function getConnection($db, $type = "read") { 
     if(array_key_exists($type, $this->_connections)) { 
      return $this->_connections[$type][$db]; 
     } 

     if($type != self::READ || $type != self::WRITE) { 
      return false; 
     } 

     $this->_connections[$type][$db] = mysql_connect($this->_config[$type]['host'], $this->_config[$type]['user'], $this->_config[$type]['pass']); 
     mysql_select_db($db, $this->_connections[$type][$db]); 
     return $this->_connections; 
    } 

} 

使用将沿着线走

这是一个非常基本的例子,但我想你会想到如何管理主/从连接。

+0

谢谢Mikushi,节省了我们的时间小时... ... – Harsha 2011-02-02 05:16:33

1

如果您使用PHP 5.3和mysqlnd驱动程序,您可以添加mysqlnd_ms插件,它将在驱动程序级别处理读取/写入分离,因此您的代码中无需修改(适用于mysql,mysqli,PDO连接库)。

欲了解更多信息阅读: http://pecl.php.net/package/mysqlnd_ms http://www.slideshare.net/nixnutz/mysqlnd-quick-overview2011

相关问题