异步Mysql客户端

AsyncMysql::query($sql, $usePool = true)

第二个参数设为false将不会使用连接池中的资源,默认都会从连接池中取,配置连接池数量 => config/database.php

具体使用
  1. use AsyncMysql;
  2. //设置超时时间
  3. AsyncMysql::setTimeout(2);
  4. $res = (yield AsyncMysql::query("INSERT INTO `user` (`id`, `mobile`, `password`)
  5. VALUES (NULL, '18768122222', '11111')"));
  6. //失败返回false
  7. if ($res) {
  8. $result = $res->getResult();
  9. $affectedRows = $res->getAffectedRows();
  10. $id = $res->getInsertId();
  11. }

异步Mysql事务处理

与传统事务一样使用,只是需要加上yield关键词,以异步方式调用

  1. use AsyncMysql;
  2. public function test()
  3. {
  4. try {
  5. yield AsyncMysql::begin();
  6. $res = (yield $this->doTrans());
  7. if ($res === false) {
  8. throw new \Exception("need roll back");
  9. }
  10. yield AsyncMysql::commit();
  11. } catch (\Exception $e) {
  12. yield AsyncMysql::rollback();
  13. }
  14. }
  15. public function doTrans()
  16. {
  17. $res = (yield AsyncMysql::query("INSERT INTO `user` (`id`, `mobile`, `password`)
  18. VALUES (NULL, '187681343332', '11111')"));
  19. if ($res) {
  20. $result = $res->getResult();
  21. $affectedRows = $res->getAffectedRows();
  22. $id = $res->getInsertId();
  23. $res = (yield AsyncMysql::query("SELECT * FROM `user` WHERE id = {$id}"));
  24. $res = (yield AsyncMysql::query("SELECT * FROM `user`"));
  25. $res = (yield AsyncMysql::query("DELETE FROM `user` WHERE id = {$id}", false));
  26. }
  27. yield true;
  28. }