Home Backend Development PHP Tutorial Detailed explanation of thinkphp distributed database

Detailed explanation of thinkphp distributed database

Jun 15, 2018 am 11:36 AM
thinkphp database

1. What is a distributed database:

The distributed database of tp is mainly configured through this configuration:

 'DB_DEPLOY_TYPE' => 1,// Database deployment method: 0 centralized (single server), 1 distributed (master-slave server)

2. What is the read-write separation of the master-slave server:

The master-slave database means that a master database has n corresponding slave databases, while a slave database can only have one corresponding slave database. Write operations in the master-slave database require the use of the master database, while read operations use the slave database. The master database and the slave database always maintain data consistency. The principle of keeping the database consistent is that when the master database data changes, the operation will be written to the master database log, and the slave database will continue to read the master database log and save it to its own log system, and then execute it. , thus keeping the master-slave database consistent.

3. Detailed explanation

1. Single database Connection

When used, the connection configuration of a single database is very simple. We only need to configure some information in the configuration file.

'DB_TYPE' => 'mysql',
'DB_HOST' => '192.168.5.102',
'DB_NAME' => 'databasename',
'DB_USER' => 'user',
'DB_PWD' => 'password',
'DB_PORT' => '3306',
'DB_PREFIX' => 'onmpw_',
Copy after login

It can be used after the setting is completed. The default is a single database connection.

2. Distributed database connection

The connection to a single database is very simple. Let’s focus on the analysis of the distributed database connection.

'DB_TYPE' => 'mysql',
'DB_HOST' => '192.168.5.191,192.168.5.88,192.168.5.103',
'DB_NAME' => 'test,test,test',
'DB_USER' => 'masteruser,slaveuser,slaveuser',
'DB_PWD' => 'masterpass,slavepass,slavepass',
'DB_PORT' => '3306',
'DB_PREFIX' => '',
'DB_DEPLOY_TYPE'        =>  1, // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
'DB_RW_SEPARATE'        =>  true,       // 数据库读写是否分离 主从式有效
'DB_MASTER_NUM'         =>  1, // 读写分离后 主服务器数量
'DB_SLAVE_NO'           =>  '', // 指定从服务器序号
Copy after login

Follow the above configuration to connect to the distributed database.

Let’s look at the following options

'DB_HOST'

Distributed database, if there are several servers, you need to fill in several server addresses. Separate each address with a comma. If it is master-slave distribution, the previous address must be the address of the master database.

对于下面的用户名和密码还有监听端口之类的,当然是有几个就写几个。如果各个数据库的用户名和密码都一样的话,可以只写一个。

对于这些选项的解析的代码如下

$_config['username']  =   explode(',',$this->config['username']);
$_config['password']  =   explode(',',$this->config['password']);
$_config['hostname']  =   explode(',',$this->config['hostname']);
$_config['hostport']   =   explode(',',$this->config['hostport']);
$_config['database']  =   explode(',',$this->config['database']);
$_config['dsn']      =   explode(',',$this->config['dsn']);
$_config['charset']   =   explode(',',$this->config['charset']);
Copy after login

‘DB_DEPLOY_TYPE’=>1

1 表示是分布式, 0 表示的是集中式(也就是单一服务器)。

该选项的实现是在类 Think\Db\Dirver中

protected function initConnect($master=true) {
    if(!empty($this->config['deploy']))
       // 采用分布式数据库
       $this->_linkID = $this->multiConnect($master);
    else
       // 默认单数据库
       if ( !$this->_linkID ) $this->_linkID = $this->connect();
}
Copy after login

$this->config[‘deploy’]表示的就是’DB_DEPLOY_TYPE’这个配置选项,上面的配置在使用之前都已经经过解析了,配置项都在$this->config数组中。至于是如何解析配置文件的,这里我们不做介绍,感兴趣的可以参考Think\Db类。

$this->multiConnect()函数就是用来进行分布式连接的,如果’DB_DEPLOY_TYPE’选项设置为1,该函数就会执行。否则直接执行$this->connect()函数。

‘DB_RW_SEPARATE’=>true

true 表示读写分离;false表示读写不分离。

这里需要注意的是,读写分离是以主从式数据库系统为前提的。该选项设置为true的时候主数据库写,从数据库读。

if($this->config['rw_separate']){
      // 主从式采用读写分离
      if($master)
          // 主服务器写入
          $r  =   $m;
      else{
          if(is_numeric($this->config['slave_no'])) {// 指定服务器读
              $r = $this->config['slave_no'];
          }else{
               // 读操作连接从服务器
              $r = floor(mt_rand($this->config['master_num'],count($_config['hostname'])-1));   // 每次随机连接的数据库
          }
            }
}else{
      // 读写操作不区分服务器
      $r = floor(mt_rand(0,count($_config['hostname'])-1));   // 每次随机连接的数据库
}
Copy after login

$this->config[‘rw_separate’] 为true的时候采用读写分离,为false的时候读写不分离。读写分离为什么必须是主从式的呢?因为从服务器不能写只能读,如果向从服务器写入数据的话,数据是没法同步的。这样就会造成数据不一致的情况。所以说,如果我们的系统是主从式的话,我们必须采用读写分离。也就是说DB_RW_SEPARATE选项必须配置为true。

'DB_MASTER_NUM'=>1

该选项后面的数字表示读写分离后,主服务器的数量。因此该选项也是用于主从式数据库系统。

下面的代码是选择主服务器。

$m = floor(mt_rand(0,$this->config['master_num']-1));

主从式数据库读取的时候选择从服务器读的核心代码

$r = floor(mt_rand($this->config['master_num'],count($_config['hostname'])-1)); // 每次随机连接的数据库

其中$this->config[‘master_num’]表示主服务器的数量。

'DB_SLAVE_NO'=> ''

指定从服务器的序号,用于读取数据。如果不设置,则根据主服务器的数量计算书从服务器的数量,然后从中随机选取一台进行读取。

if(is_numeric($this->config['slave_no'])) {// 指定服务器读
$r = $this->config['slave_no'];
}else{
// 读操作连接从服务器
$r = floor(mt_rand($this->config['master_num'],count($_config['hostname'])-1)); // 每次随机连接的数据库
}

以上是对每个选项的作用的实现代码进行了一个简单的说明。

下面我们来看其连接的部分

if($m != $r ){
   $db_master  =  array(
      'username' =>  isset($_config['username'][$m])?$_config['username'][$m]:$_config['username'][0],
      'password'  =>  isset($_config['password'][$m])?$_config['password'][$m]:$_config['password'][0],
      'hostname'  =>  isset($_config['hostname'][$m])?$_config['hostname'][$m]:$_config['hostname'][0],
      'hostport'  =>  isset($_config['hostport'][$m])?$_config['hostport'][$m]:$_config['hostport'][0],
      'database'  =>  isset($_config['database'][$m])?$_config['database'][$m]:$_config['database'][0],
      'dsn'  =>  isset($_config['dsn'][$m])?$_config['dsn'][$m]:$_config['dsn'][0],
      'charset'  =>  isset($_config['charset'][$m])?$_config['charset'][$m]:$_config['charset'][0],
    );
}
$db_config = array(
   'username'  =>  isset($_config['username'][$r])?$_config['username'][$r]:$_config['username'][0],
    'password'  =>  isset($_config['password'][$r])?$_config['password'][$r]:$_config['password'][0],
    'hostname'  =>  isset($_config['hostname'][$r])?$_config['hostname'][$r]:$_config['hostname'][0],
    'hostport'  =>  isset($_config['hostport'][$r])?$_config['hostport'][$r]:$_config['hostport'][0],
     'database'  =>  isset($_config['database'][$r])?$_config['database'][$r]:$_config['database'][0],
     'dsn'  =>  isset($_config['dsn'][$r])?$_config['dsn'][$r]:$_config['dsn'][0],
     'charset'   =>  isset($_config['charset'][$r])?$_config['charset'][$r]:$_config['charset'][0],
);
return $this->connect($db_config,$r,$r == $m ? false : $db_master);
Copy after login

看到这,我觉得大家应该对上面在介绍各个配置选项的代码的时候其中的$r和$m是什么作用了。

现在我们来看 $r == $m ? false : $db_master ,如果数据库读写不分离的情况下,读写是一台服务器的话 传给connect函数的值为false。或者是如果是主从分离的写的情况下传给connect的值也为false。通过上面代码我们看到,如果$r和$m不相等的情况下,会设置$db_master。其实也就是相当于一台备用的,如果选择的$r服务器出现故障不能连接,将会去连接$db_master。

connect()函数的第三个参数其实是表示当$db_config这台服务器连接故障时是否选择备用的连接。false表示不重连,其它值即表示重新连接。

其核心代码如下

try{
   if(empty($config['dsn'])) {
      $config['dsn']  =   $this->parseDsn($config);
   }
   if(version_compare(PHP_VERSION,&#39;5.3.6&#39;,&#39;<=&#39;)){
       // 禁用模拟预处理语句
       $this->options[PDO::ATTR_EMULATE_PREPARES]  =   false;
   }
   $this->linkID[$linkNum] = new PDO( $config[&#39;dsn&#39;], $config[&#39;username&#39;], $config[&#39;password&#39;],$this->options);
}catch (\PDOException $e) {
   if($autoConnection){ //$autoConnection不为false,而是默认的主服务器
        trace($e->getMessage(),&#39;&#39;,&#39;ERR&#39;);
            return $this->connect($autoConnection,$linkNum);  //出现异常,使用递归函数重新连接
        }elseif($config[&#39;debug&#39;]){
            E($e->getMessage());
    }
}
Copy after login

这种方式,对于主从式来说,$r和$m肯定不会相同。因此如果说在读取数据的时候,选择的那台从服务器出现故障的话,那主服务器即是备用的,最后会去主服务器读取。能保证数据读取的时效性。

本文讲解了thinkphp 分布式数据库详解,更多相关内容请关注php中文网。

相关推荐:

如何通过ThinkPHP链接数据库

如何通过thinkphp连接多数据库

关于ThinkPHP 5.数据库的一些基本操作

The above is the detailed content of Detailed explanation of thinkphp distributed database. For more information, please follow other related articles on the PHP Chinese website!

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)

iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos Jul 18, 2024 am 05:48 AM

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

How does Hibernate implement polymorphic mapping? How does Hibernate implement polymorphic mapping? Apr 17, 2024 pm 12:09 PM

Hibernate polymorphic mapping can map inherited classes to the database and provides the following mapping types: joined-subclass: Create a separate table for the subclass, including all columns of the parent class. table-per-class: Create a separate table for subclasses, containing only subclass-specific columns. union-subclass: similar to joined-subclass, but the parent class table unions all subclass columns.

Detailed tutorial on establishing a database connection using MySQLi in PHP Detailed tutorial on establishing a database connection using MySQLi in PHP Jun 04, 2024 pm 01:42 PM

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

How to handle database connection errors in PHP How to handle database connection errors in PHP Jun 05, 2024 pm 02:16 PM

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

How to connect to remote database using Golang? How to connect to remote database using Golang? Jun 01, 2024 pm 08:31 PM

Through the Go standard library database/sql package, you can connect to remote databases such as MySQL, PostgreSQL or SQLite: create a connection string containing database connection information. Use the sql.Open() function to open a database connection. Perform database operations such as SQL queries and insert operations. Use defer to close the database connection to release resources.

How to use database callback functions in Golang? How to use database callback functions in Golang? Jun 03, 2024 pm 02:20 PM

Using the database callback function in Golang can achieve: executing custom code after the specified database operation is completed. Add custom behavior through separate functions without writing additional code. Callback functions are available for insert, update, delete, and query operations. You must use the sql.Exec, sql.QueryRow, or sql.Query function to use the callback function.

How to save JSON data to database in Golang? How to save JSON data to database in Golang? Jun 06, 2024 am 11:24 AM

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

How to handle database connections and operations using C++? How to handle database connections and operations using C++? Jun 01, 2024 pm 07:24 PM

Use the DataAccessObjects (DAO) library in C++ to connect and operate the database, including establishing database connections, executing SQL queries, inserting new records and updating existing records. The specific steps are: 1. Include necessary library statements; 2. Open the database file; 3. Create a Recordset object to execute SQL queries or manipulate data; 4. Traverse the results or update records according to specific needs.

See all articles