Describes how yii2 implements database/table sharding.
Preface
You can start code tracing from any gii generation model class, and you will find that the model layer of yii2 implements DAO access to the database based on ActiveRecord.
The inheritance chain of ActiveRecord can continue to be traced. In the end, model is actually a component, and component is an important component of IOC in yii2. It provides behaviors and event capabilities for extension of successors.
(For more information about IOC, component, behaviors, and event, see http://www.digpage.com)
First, let alone the above concepts. The development history of a website is generally one database, one table, one database, N tables, and M databases, N tables, the following uses the order table as an example to describe it separately.
1) database 1 Table: yii2 uses PDO to connect to mysql by default. By default, the Framework configures a component called db as the unique mysql connection object. The dsn assigns the database address and name, the configuration is as follows:
'components' => [ 'db' => [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=10.10.10.10;port=4005;dbname=wordpress', 'username' => 'wp', 'password' => '123', 'charset' => 'utf8', ],
This is a typical example of IOC in yii2. By default, the db in the model layer is used as the mysql connection object. Therefore, model access passes through this connection and can be seen from the ActiveRecord class.
class ActiveRecord extends BaseActiveRecord { /** * Returns the database connection used by this AR class. * By default, the "db" application component is used as the database connection. * You may override this method if you want to use a different database connection. * @return Connection the database connection used by this AR class. */public static function getDb(){ return Yii::$app->getDb();}
After tracing, the component named "db" will be created using the ioc of yii2 and returned to the model layer.
abstract class Application extends Module {/** * Returns the database connection component. * @return \yii\db\Connection the database connection. */public function getDb(){ return $this->get('db');}
The above implementation of yii2 determines that only one database server can be connected and one database is selected. The specific table accessed is implemented by overwriting the tableName static method in the Model, activeRecord determines the table name based on the overwrite tableName.
class OrderInfo extends \yii\db\ActiveRecord{ /** * @inheritdoc * @return */ public static function tableName() { return 'order_info'; }
2) database 1 N table: As the orderInfo data volume increases, performance indicators in various aspects are reduced, while the single-host hardware performance is also redundant, you can consider dividing multiple order_info tables to evenly share the data volume. Suppose we want to make eight tables, then we can decide which table the order is stored in based on uid (User ID) % 8.
However, in database 1 and table 1,tableName()The returned value is order_info. Therefore, we can reload this function to provide a dynamic change capability. For example:
Class OrderInfo extends \ yii \ db \ ActiveRecord {private static $ partitionIndex _ = null; // shard ID/*** reset partition id * @ param unknown $ uid */private static function resetPartitionIndex ($ uid = null) {$ partitionCount = \ Yii :: $ app-> params ['order'] ['partitioncount']; self: $ partitionIndex _ = $ uid % $ partitionCount ;} /*** @ inheritdoc */public static function tableName () {return 'order _ info '. self: $ partitionIndex _;}
ProvideresetParitionIndex($uid)Function, which is called to mark the subscript of a table shard before each model operation, and reload tableName to splice the table name of this operation for the model layer.
3) M database N tables: 1 Database N tables gradually develop, and the performance of standalone storage reaches the bottleneck. data can only be distributed to multiple servers for storage, so the demand for database sharding is raised. However, according to the implementation logic of the "database 1 and table 1" framework, if the model layer uses the db configuration as the mysql connection by default, there is no way to access multiple mysql instances, therefore, you must solve this problem.
Generally, this demand has entered the stage of steady development in the middle. There are two ways to solve the M database problem. One is that yii2 accesses multiple databases by directly connecting multiple addresses, and the other is that yii2 still connects only one address, this address is deployed with dbproxy, which connects multiple databases based on the database name proxy you visit.
If you have not mastered dbproxy and the php cluster size is not as large as the number of client connections in a single mysql instance is too large to reject the service, then you can solve the problem by using 1st solutions. Otherwise, select 2nd solutions.
No matter which solution we choose, we should make further improvements.tableName()Function that provides the ability to dynamically change database names, similar to dynamic table changes.
Class OrderInfo extends \ yii \ db \ ActiveRecord {private static $ databaseIndex _ = null; // database shard IDprivate static $ partitionIndex _ = null; // shard ID/*** reset partition id * @ param unknown $ uid */private static function resetPartitionIndex ($ uid = null) {$ databaseCount = \ Yii :: $ app-> params ['order'] ['databasecount']; $ partitionCount = \ Yii: $ app-> params ['order'] ['partitioncount']; // determine the table to which the table is assigned self: $ partitionIndex _ = $ uid % $ partitionCount; // determine the database self to which the table is assigned based on the table Subscript :: $ databaseIndex _ = intval (self: $ partitionIndex _/($ partitionCount/$ databaseCount);}/*** @ inheritdoc */public static function tableName () {$ database = 'wordpress '. self: $ databaseIndex _; $ table = 'order _ info '. self: $ partitionIndex _; return $ database. '. '. $ table ;}
You can implement database sharding by slightly modifying the table sharding logic. Suppose there are eight tables, which are respectively... 07, and then decided to divide the four databases, then the tables are in the 00 database, the tables are in the 01 database, the tables are in the 02 database, and the tables are in the 03 database, the calculation code corresponding to this rule is as follows. Code that will eventually take effect for ActiveRecord will be similar"select * from wordpress0.order_info1", This will solve the need to connect to dbproxy to access multiple databases.
How can yii directly access multiple Mysql instances?tableName(), We only need to overwritegetDb()At the same time, we need to configure four mysql instances first, so that multiple db connections can be generated through the application of yii through IOC design. All the changes are as follows:
Configure the four databases and give different component IDs for differentiation. they connect to different mysql instances. The dbname in dsn only needs to exist (to prevent PDO execution ).use databaseWhen there is no error), the real database name istableName()Dynamically changed.
'db0' => [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=10.10.10.10;port=6184;dbname=wordpress0', 'username' => 'wp', 'password' => '123', 'charset' => 'utf8', // 'tablePrefix' => 'ktv_',],'db1' => [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=10.10.10.11;port=6184;dbname=wordpress2', 'username' => 'wp', 'password' => '123', 'charset' => 'utf8', // 'tablePrefix' => 'ktv_',],'db2' => [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=10.10.10.12;port=6184;dbname=wordpress4', 'username' => 'wp', 'password' => '123', 'charset' => 'utf8', // 'tablePrefix' => 'ktv_',],'db3' => [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=10.10.10.13;port=6184;dbname=wordpress6', 'username' => 'wp', 'password' => '123', 'charset' => 'utf8', // 'tablePrefix' => 'ktv_',],
OverwritegetDb()Method: return different database connections according to the database subscript.
Class OrderInfo extends \ yii \ db \ ActiveRecord {private static $ databaseIndex _ = null; // database shard ID private static $ partitionIndex _ = null; // shard ID/*** reset partition id * @ param unknown $ uid */private static function resetPartitionIndex ($ uid = null) {$ databaseCount = \ Yii :: $ app-> params ['order'] ['databasecount']; $ partitionCount = \ Yii: $ app-> params ['order'] ['partitioncount']; // determine the table to which the table is assigned self: $ partitionIndex _ = $ uid % $ partitionCount; // determine the database self to which the table is assigned based on the table Subscript :: $ databaseIndex _ = intval (self: $ partitionIndex _/($ partitionCount/$ databaseCount);}/*** returns the database name based on database/table sharding. table name */public static function tableName () {$ database = 'wordpress '. self: $ databaseIndex _; $ table = 'order _ info '. self: $ partitionIndex _; return $ database. '. '. $ table;}/*** different database connections are returned based on the database sharding result */public static function getDb () {return \ Yii :: $ app-> get ('db '. self: $ databaseIndex _);}
In this way, yii can be used to connect multiple mysql instances or yii to connect one dbproxy.
There are some examples on the internet, trying to use the component event mechanism to implicitly (automatically) hook different DAO operations by specifying custom events such as onUpdate and onBeforeSave in component configuration) the database, connection, or tablename change method is implemented based on the model object.updateAll()If DAO is bypassed and PDO is taken directly, these events are not triggered, so it is not a complete solution.
This solution is simple in principle and has no intrusion into the framework, but must be explicitly stated before each DB operation.resetPartitionIndex($uid)Call. To avoid user perception, the ActiveRecord class must be inherited to further overwrite the implementation of all class methods so that the logic of inserting the selected database and table is too costly.
Supplement:For some practical details about database/table sharding, we recommend that you set the number of table shards to 2 ^ n. For example, if n = 3, you can divide the number of tables into 8, and then determine the number of databases. The number of databases is 2 ^ m, however, you need to <= the number of tables. For example, one database, two databases, four databases, and eight databases are allowed. The table order is located in these databases.
Why are the numbers both 2 indexes? The reason is that data migration is easier if you are facing expansion requirements. Assume that two tables are divided, and the data is scattered by uid % 2. To expand to four tables, you only need to migrate part of the data in Table 0 to table 2, migrate part of the data in table 1 to table 3 to complete the expansion, that is, the migration caused by uid % 2 and uid % 4 is very small. You can calculate this by yourself.
Summary
The above is all about yii2's implementation of database/table sharding. I hope this article will help you in your study or work. If you have any questions, please leave a message.