Home Backend Development PHP Tutorial Yii实现多数据库主从读写分离的方法_PHP

Yii实现多数据库主从读写分离的方法_PHP

May 31, 2016 pm 01:18 PM
yii separation Multiple databases Read and write

本文实例讲述了Yii实现多数据库主从读写分离的方法。分享给大家供大家参考。具体分析如下:

Yii框架数据库多数据库、主从、读写分离 实现,功能描述:

1.实现主从数据库读写分离 主库:写 从库(可多个):读

2.主数据库无法连接时 可设置从数据库是否 可写

3.所有从数据库无法连接时 可设置主数据库是否 可读

4.如果从数据库连接失败 可设置N秒内不再连接

利用yii扩展实现,代码如下:

代码如下:

/**
 * 主数据库 写 从数据库(可多个)读
 * 实现主从数据库 读写分离 主服务器无法连接 从服务器可切换写功能
 * 从务器无法连接 主服务器可切换读功
 * by lmt
 * */
class DbConnectionMan extends CDbConnection {
    public $timeout = 10; //连接超时时间
    public $markDeadSeconds = 600; //如果从数据库连接失败 600秒内不再连接 
    //用 cache 作为缓存全局标记
    public $cacheID = 'cache';
 
    /**
     * @var array $slaves.Slave database connection(Read) config array.
     * 配置符合 CDbConnection.
     * @example
     * 'components'=>array(
     *   'db'=>array(
     *    'connectionString'=>'mysql://',
     *    'slaves'=>array(
     *     array('connectionString'=>'mysql://'),
     *     array('connectionString'=>'mysql://'),
     *    )
     *   )
     * )
     * */
    public $slaves = array();
    /**
     * 
     * 从数据库状态 false 则只用主数据库
     * @var bool $enableSlave
     * */
    public $enableSlave = true;
 
    /**
     * @var slavesWrite 紧急情况主数据库无法连接 切换从服务器(读写).
     */
    public $slavesWrite = false;
 
    /**
     * @var masterRead 紧急情况从主数据库无法连接 切换从住服务器(读写).
     */
    public $masterRead = false;
 
    /**
     * @var _slave
     */
    private $_slave;
 
    /**
     * @var _disableWrite 从服务器(只读).
     */
    private $_disableWrite = true;
 
    /**
     *
     * 重写 createCommand 方法,1.开启从库 2.存在从库 3.当前不处于一个事务中 4.从库读数据
     * @param string $sql
     * @return CDbCommand
     * */
    public function createCommand($sql = null) {
        if ($this->enableSlave && !emptyempty($this->slaves) && is_string($sql) && !$this->getCurrentTransaction() && self::isReadOperation($sql) && ($slave = $this->getSlave())
        ) {
            return $slave->createCommand($sql);
        } else {
            if (!$this->masterRead) {
                if ($this->_disableWrite && !self::isReadOperation($sql)) {
 
                    throw new CDbException("Master db server is not available now!Disallow write operation on slave server!");
                }
            }
            return parent::createCommand($sql);
        }
    }
 
    /**
     * 获得从服务器连接资源
     * @return CDbConnection
     * */
    public function getSlave() {
        if (!isset($this->_slave)) {
            shuffle($this->slaves);
            foreach ($this->slaves as $slaveConfig) {
                if ($this->_isDeadServer($slaveConfig['connectionString'])) {
                    continue;
                }
                if (!isset($slaveConfig['class']))
                    $slaveConfig['class'] = 'CDbConnection';
 
                $slaveConfig['autoConnect'] = false;
                try {
                    if ($slave = Yii::createComponent($slaveConfig)) {
                        Yii::app()->setComponent('dbslave', $slave);
                        $slave->setAttribute(PDO::ATTR_TIMEOUT, $this->timeout);
                        $slave->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
                        $slave->setActive(true);
                        $this->_slave = $slave;
                        break;
                    }
                } catch (Exception $e) {
                    $this->_markDeadServer($slaveConfig['connectionString']);
                    Yii::log("Slave database connection failed!ntConnection string:{$slaveConfig['connectionString']}", 'warning');
 
                    continue;
                }
            }
 
            if (!isset($this->_slave)) {
                $this->_slave = null;
                $this->enableSlave = false;
            }
        }
        return $this->_slave;
    }
 
    public function setActive($value) {
        if ($value != $this->getActive()) {
            if ($value) {
                try {
                    if ($this->_isDeadServer($this->connectionString)) {
                        throw new CDbException('Master db server is already dead!');
                    }
                    //PDO::ATTR_TIMEOUT must set before pdo instance create
                    $this->setAttribute(PDO::ATTR_TIMEOUT, $this->timeout);
                    $this->open();
                } catch (Exception $e) {
                    $this->_markDeadServer($this->connectionString);
                    $slave = $this->getSlave();
                    Yii::log($e->getMessage(), CLogger::LEVEL_ERROR, 'exception.CDbException');
                    if ($slave) {
                        $this->connectionString = $slave->connectionString;
                        $this->username = $slave->username;
                        $this->password = $slave->password;
                        if ($this->slavesWrite) {
                            $this->_disableWrite = false;
                        }
                        $this->open();
                    } else { //Slave also unavailable
                        if ($this->masterRead) {
                            $this->connectionString = $this->connectionString;
                            $this->username = $this->username;
                            $this->password = $this->password;
                            $this->open();
                        } else {
                            throw new CDbException(Yii::t('yii', 'CDbConnection failed to open the DB connection.'), (int) $e->getCode(), $e->errorInfo);
                        }
                    }
                }
            } else {
                $this->close();
            }
        }
    }
 
    /**
     * 检测读操作 sql 语句
     * 
     * 关键字: SELECT,DECRIBE,SHOW ...
     * 写操作:UPDATE,INSERT,DELETE ...
     * */
    public static function isReadOperation($sql) {
        $sql = substr(ltrim($sql), 0, 10);
        $sql = str_ireplace(array('SELECT', 'SHOW', 'DESCRIBE', 'PRAGMA'), '^O^', $sql); //^O^,magic smile
        return strpos($sql, '^O^') === 0;
    }
 
    /**
     * 检测从服务器是否被标记 失败.
     */
    private function _isDeadServer($c) {
        $cache = Yii::app()->{$this->cacheID};
        if ($cache && $cache->get('DeadServer::' . $c) == 1) {
            return true;
        }
        return false;
    }
 
    /**
     * 标记失败的slaves.
     */
    private function _markDeadServer($c) {
        $cache = Yii::app()->{$this->cacheID};
        if ($cache) {
            $cache->set('DeadServer::' . $c, 1, $this->markDeadSeconds);
        }
    }
}


main.php配置:components 数组中,代码如下:

代码如下:

'db'=>array(
        'class'=>'application.extensions.DbConnectionMan',//扩展路径
        'connectionString' => 'mysql:host=192.168.1.128;dbname=db_xcpt',//主数据库 写
        'emulatePrepare' => true,
        'username' => 'root',
        'password' => 'root',
        'charset' => 'utf8',
        'tablePrefix' => 'xcpt_', //表前缀
        'enableSlave'=>true,//从数据库启用
   'urgencyWrite'=>true,//紧急情况 主数据库无法连接 启用从数据库 写功能
    'masterRead'=>true,//紧急情况 从数据库无法连接 启用主数据库 读功能
        'slaves'=>array(//从数据库
            array(   //slave1
                'connectionString'=>'mysql:host=localhost;dbname=db_xcpt',
                'emulatePrepare' => true,
                'username'=>'root',
                'password'=>'root',
                'charset' => 'utf8',
                'tablePrefix' => 'xcpt_', //表前缀
            ),
   array(   //slave2
                'connectionString'=>'mysql:host=localhost;dbname=db_xcpt',
                'emulatePrepare' => true,
                'username'=>'root',
                'password'=>'root',
                'charset' => 'utf8',
                'tablePrefix' => 'xcpt_', //表前缀
            ),
 
        ),
),

希望本文所述对大家基于Yii框架的php程序设计有所帮助。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use PHP to implement data caching, reading and writing functions How to use PHP to implement data caching, reading and writing functions Sep 05, 2023 pm 05:45 PM

How to use PHP to implement data caching and read-write functions. Caching is an important way to improve system performance. Through caching, frequently used data can be stored in memory to increase the reading speed of data. In PHP, we can use various methods to implement data caching and reading and writing functions. This article will introduce two common methods: using file caching and using memory caching. 1. Use file caching. File caching stores data in files for subsequent reading. The following is a sample code that uses file caching to read and write data:

How to use PHP framework Yii to develop a highly available cloud backup system How to use PHP framework Yii to develop a highly available cloud backup system Jun 27, 2023 am 09:04 AM

With the continuous development of cloud computing technology, data backup has become something that every enterprise must do. In this context, it is particularly important to develop a highly available cloud backup system. The PHP framework Yii is a powerful framework that can help developers quickly build high-performance web applications. The following will introduce how to use the Yii framework to develop a highly available cloud backup system. Designing the database model In the Yii framework, the database model is a very important part. Because the data backup system requires a lot of tables and relationships

How to use the module system in Java 9 to separate and isolate code How to use the module system in Java 9 to separate and isolate code Jul 30, 2023 pm 07:46 PM

How to use the module system in Java 9 to separate and isolate code As the scale of software continues to expand, the complexity of the code continues to increase. In order to better organize and manage code, Java9 introduced the module system. The emergence of the module system solves the problem of traditional package dependencies, making the separation and isolation of code easier and more flexible. This article will introduce how to use the module system in Java 9 to achieve code separation and isolation. 1. Definition of module In Java9, we can use the module keyword to define

Symfony vs Yii2: Which framework is better for developing large-scale web applications? Symfony vs Yii2: Which framework is better for developing large-scale web applications? Jun 19, 2023 am 10:57 AM

As the demand for web applications continues to grow, developers have more and more choices in choosing development frameworks. Symfony and Yii2 are two popular PHP frameworks. They both have powerful functions and performance, but when faced with the need to develop large-scale web applications, which framework is more suitable? Next we will conduct a comparative analysis of Symphony and Yii2 to help you make a better choice. Basic Overview Symphony is an open source web application framework written in PHP and is built on

Suggestions on front-end technology selection in Golang front-end and back-end separation development. Suggestions on front-end technology selection in Golang front-end and back-end separation development. Mar 05, 2024 pm 12:12 PM

Title: Suggestions on front-end technology selection in Golang front-end and back-end separation development As the complexity and demands of web applications continue to increase, the front-end and back-end separation development model is becoming more and more popular. In this development model, the backend is responsible for processing business logic, and the frontend is responsible for displaying pages and interacting with users. The two communicate through APIs. For development teams using Golang as a back-end language, choosing the right front-end technology is crucial. This article will discuss the recommended front-end technologies to choose in the separate development of front-end and back-end in Golang, and

Multi-database support tips in Django framework Multi-database support tips in Django framework Jun 18, 2023 am 10:52 AM

Django is a popular Python web framework. Its excellent ORM (Object Relational Mapping) mechanism allows developers to easily operate databases. However, in some actual projects, multiple databases need to be connected. At this time, some skills are needed to ensure the stability and development efficiency of the project. In Django, multi-database support is based on the functions provided by the Django framework itself. Here, we will introduce some multi-database support tips to help you better develop in Django

Data query in Yii framework: access data efficiently Data query in Yii framework: access data efficiently Jun 21, 2023 am 11:22 AM

The Yii framework is an open source PHP Web application framework that provides numerous tools and components to simplify the process of Web application development, of which data query is one of the important components. In the Yii framework, we can use SQL-like syntax to access the database to query and manipulate data efficiently. The query builder of the Yii framework mainly includes the following types: ActiveRecord query, QueryBuilder query, command query and original SQL query

How to use Yii3 framework in php? How to use Yii3 framework in php? May 31, 2023 pm 10:42 PM

As the Internet continues to develop, the demand for web application development is also getting higher and higher. For developers, developing applications requires a stable, efficient, and powerful framework, which can improve development efficiency. Yii is a leading high-performance PHP framework that provides rich features and good performance. Yii3 is the next generation version of the Yii framework, which further optimizes performance and code quality based on Yii2. In this article, we will introduce how to use Yii3 framework to develop PHP applications.

See all articles