akalend/mysql_shard

数据库扩展MySQL客户端,用于数据库扩展

dev-master 2019-01-28 18:43 UTC

This package is not auto-updated.

Last update: 2024-09-20 22:06:57 UTC


README

mysqlnd驱动程序上的客户端包装,用于数据库扩展

##基本

分片 - 是将大逻辑表分割成多个小物理表的方法。CONFEDERATED Mysql表的类型是简单的分片。

分片策略 是数据库记录按物理表进行分布的算法。

分片标准 是将记录发送到某个数据库表的函数或规则。

#要求

  • MySQL 5.0 或更高版本
  • Redis 2.0 或更高版本

如果您使用其他Kyy/Value NoSQL(非Redis),您可以使用它。例如,MemcacheDb,Tarantool或AeroSpike。给我发消息,我会为您的存储引擎添加新的PHP类。

##使用分片策略

  • 线性
  • 循环
  • 每月
  • 地理(开发中)

##线性分片

分片使用递增ID和数据填充一个表(table_0),然后另一个表(table_1),依此类推(table_2, table_3 ...)。

插入示例

	<?php
	// get some data
	$data = get_some_data();

	// load config file
	$conf = Config::get('sharding');

	// MysqlShard constructor
    $sharding = new MysqlShard($conf);

	// create sharding strategy
    $strategy = new LinearStrategy(null,'lines', $sharding->getConfig());
    
    //SQL template
    $sql = "INSERT INTO %db.logdata_%t (data) VALUES('$data')";

    //execute query
    $sharding->query($sql);

选择示例

	<?php
		
	// load config file
	$conf = Config::get('sharding');

	// MysqlShard constructor
    $sharding = new MysqlShard($conf);

	// create sharding strategy $data_id is some id your data
    $strategy = new LinearStrategy($data_id,'lines', $sharding->getConfig());
        
    //query template
    $sql = "SELECT * FROM %db.logdata_%t WHERE id=$data_id";

    //executing
    $res = $sharding->query($sql);

    // get data from dataset
    $row = $res->fetch_assoc();
    var_dump($row);

##SQL模板

所以,PHP函数的查询模板有伪符号

  • %db带有数字的数据库名称,例如database_1,database_2等。
  • %t带有数字的表名称,例如tablename_1,tablename_2等。

数据库和表的名字和数字通过预定的策略计算得出。

##循环分片示例

	<?php 
		
	// load config file
	$conf = Config::get('sharding');

	// MysqlShard constructor
    $sharding = new MysqlShard($conf);

	$date = date('Y-m'); // Set current month

	// create sharding strategy $user_id is some id user profile
    $strategy = new MonthStrategy($user_id,'months', $sharding->getConfig(), $date);
        
    $sql = "INSERT INTO %db.stats_%t (data) VALUES('$data')";

    //query executing
   $res = $sharding->query($sql);

对于2016年6月20日的数据,策略创建的表名为:stats_2016_06。如果user_id=100,则数据库名称是user_id % shardCount,100 % 4 = 0;对于UserId等于100的数据,被插入到months_0.stats_2016_06 mysql表中。

##循环分片读取示例

<?php 		
	// MysqlShard constructor
    $sharding = new MysqlShard(Config::get('sharding'));

	// create sharding strategy 
    $strategy = new MonthStrategy(null,'months', $sharding->getConfig(),  date('Y-m'));

   // some query for all shards     
    $sql = "SELECT FROM %db.stats_%t (data) WHERE type_id=$x";

    $rows = [];
    foreach ($sharding as $shrdItem) {
    	//query executing
    	$res = $sharItem->query($sql);
    	while( $row = $res->fetch_assoc()) {
    		$rows[] = $row;
    	}
    }

此示例展示了如何从所有数据库(分片)中读取数据。它仅用于循环和每月策略。

##俄语文档

更多俄语说明请参阅README.rus.md