MysqlAsynPool
异步mysql连接池
普通用法
示例:
/**
* mysql 测试
* @throws \Server\CoreBase\SwooleException
*/
public function mysql_test()
{
$this->mysql_pool->dbQueryBuilder->select('*')->from('account')->where('sex', 1);
$this->mysql_pool->query(function ($result) {
print_r($result);
});
$this->destroy();
}
其中dbQueryBuilder对应的是Miner,关于用法参考Miner
协程事务
非协程版事务相对复杂不建议使用。
/**
* mysql 事务协程测试
*/
public function http_mysql_begin_coroutine_test()
{
$id = yield $this->mysql_pool->coroutineBegin($this);
$update_result = yield $this->mysql_pool->dbQueryBuilder->update('user_info')->set('sex', '0')->where('uid', 36)->coroutineSend($id);
$result = yield $this->mysql_pool->dbQueryBuilder->select('*')->from('user_info')->where('uid', 36)->coroutineSend($id);
if ($result['result'][0]['channel'] == 888) {
$this->http_output->end('commit');
yield $this->mysql_pool->coroutineCommit($id);
} else {
$this->http_output->end('rollback');
yield $this->mysql_pool->coroutineRollback($id);
}
}
协程模式
示例:
$mySqlCoroutine = $this->mysql_pool->dbQueryBuilder->select('*')->from('account')->where('uid', 10303)->coroutineSend();
$mysql_result = yield $mySqlCoroutine;
$redisCoroutine = $this->redis_pool->coroutineSend('get', 'test');
$redis_result = yield $redisCoroutine;
使用协程会大大简化代码的书写,提高代码的可读性。
上面的代码通过yield关键字返回了异步回调的值。
执行顺序 mysql_send->mysql_rev->redis_send->redis_rev;
$mySqlCoroutine = $this->mysql_pool->dbQueryBuilder->select('*')->from('account')->where('uid', 10303)->coroutineSend();
$redisCoroutine = $this->redis_pool->coroutineSend('get', 'test');
$mysql_result = yield $mySqlCoroutine;
$redis_result = yield $redisCoroutine;
执行顺序 mysql_send->redis_send->mysql_rev->redis_rev;
获取mysql语句
$value = $this->mysql_pool->dbQueryBuilder->insertInto('account')->intoColumns(['uid', 'static'])->intoValues([[36, 0], [37, 0]])->getStatement(true);