2011-01-26 51 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

相關問題