【问题标题】:Building an Web App on a Read and Write based server set在基于读写的服务器集上构建 Web 应用程序
【发布时间】:2011-01-26 21:20:24
【问题描述】:

我有一个普遍的好奇心问题。

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

在我的 Web 应用程序中,我会同时启动与主服务器和从服务器的连接吗?使用主连接仅用于发送写入和使用从连接仅用于读取数据?

【问题讨论】:

    标签: php mysql database-replication


    【解决方案1】:

    在任何情况下,您都应该根据需要处理您的主从连接,通常通过 getConnection() 函数。在我的工作设置中,2个集群,2个master,一个4个slave,另一个8个,功能基本上是这样的:

    <?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;
        }
    
    }
    

    用法大致如下:

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

    这是一个非常基本的示例,但我想您已经了解如何管理主/从连接。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-22
        • 1970-01-01
        • 2020-10-08
        相关资源
        最近更新 更多