需求分析

本篇我们将通过 Swoole 实现一个自带连接池的 MySQL 查询器:

  1. 支持通过链式调用构造并执行 SQL 语句;
  2. 支持连接池技术;
  3. 支持多协程事务并发执行(协程安全性);
  4. 支持连接对象的健康检测;
  5. 支持连接对象断线重连;
  6. 程序需要可扩展,为未来的改造留好扩展点;

完整项目地址:协程版 MySQL 查询器

(注:该项目并非示例项目,而是生产可用的,已经在公司内部稳定使用。)

使用示例

  • 查询:
  1. $query->select(['uid', 'name'])
  2. ->from('users u')
  3. ->join('auth_users au', "u.uid=au.uid")
  4. ->where(['uid' => $uid])
  5. ->groupBy("u.phone")
  6. ->having("count(u.phone)>1")
  7. ->orderBy("u.uid desc")
  8. ->limit(10, 0)
  9. ->list();
  • 插入:
  1. $query->insert('users')
  2. ->values(
  3. [
  4. [
  5. 'name' => 'linvanda',
  6. 'phone' => '18687664562',
  7. 'nickname' => '林子',
  8. ],
  9. [
  10. 'name' => 'xiake',
  11. 'phone' => '18989876543',
  12. 'nickname' => '侠客',
  13. ],
  14. ]
  15. )->execute();// 这里是批量插入,不需要批量插入的话,传入一维数组即可
  16. // 延迟插入
  17. $query->insert('users')
  18. ->delayed()
  19. ->values(
  20. [
  21. 'name' => 'linvanda',
  22. 'phone' => '18687664562',
  23. 'nickname' => '林子',
  24. ]
  25. )->execute();
  • 更新:
  1. $query->update('users u')
  2. ->join('auth_users au', "u.uid=au.uid")
  3. ->set(['u.name' => '粽子'])
  4. ->where("u.uid=:uid", ['uid' => 123])
  5. ->execute();
  • 删除:
  1. $query->delete('users')
  2. ->where("uid=:uid", ['uid' => 123])
  3. ->execute();
  • 事务:
  1. $query->begin();
  2. $query->update('users u')
  3. ->join('auth_users au', "u.uid=au.uid")
  4. ->set(['u.name' => '粽子'])
  5. ->where("u.uid=:uid", ['uid' => 123])
  6. ->execute();
  7. ...
  8. $query->commit();

模块设计

  1. 查询模块:

    • 查询器(Query,入口)
    • SQL构造器(Builder)
  2. 事务模块:
    • 事务接口(ITransaction)
    • 协程版事务类(CoTransaction)
    • 协程上下文(TContext)
  3. 连接池模块:
    • 连接池接口(IPool)
    • 协程连接池类(CoPool)
  4. 数据库连接(驱动)模块:
    • 连接接口(IConnector)
    • 连接生成器接口(IConnectorBuilder)
    • 协程连接类(CoConnector)
    • 协程连接生成器(CoConnectorBuilder)
    • 数据库连接配置类(DBConfig)
    • 数据库连接(统计)信息类(ConnectorInfo)

我们希望通过统一的入口对外提供服务,将复杂性隐藏在内部。该统一入口由查询模块提供。该模块由查询器SQL 构造器构成,其中查询器作为外界唯一入口,而构造器是一个 Trait,因为这样可以让外界通过查询器入口直接使用构造器提供的 SQL 组装功能。

查询器通过事务模块执行 SQL。这里的事务有两个层面含义:数据库操作的事务性(显式或隐式事务,由 CoTransaction 类保障),以及多协程下的执行环境隔离性(由 TContext 类保障)。

事务模块需要通过数据库连接对象执行具体的 SQL。连接对象由连接池模块提供。

连接池模块维护(创建、回收、销毁)数据库连接对象,具体是通过数据库连接模块的连接生成器生成新数据库连接。

模块之间依赖于接口而非具体实现:查询模块依赖事务模块的 ITransaction 接口;事务模块依赖连接池模块的 IPool 接口和数据库连接模块的 IConnector 接口;连接池模块依赖数据库连接模块的 IConnectorBuilder 接口。

UML 类图

下面,我们分模块具体讲解。

入口

由查询模块对外提供统一的使用入口。查询模块由两部分构成:查询器和 SQL 构造器。为了让调用方可以直接通过查询器来构造 SQL(而不用先实例化一个构造器构造 SQL 然后传给查询器),我将构造器设计成 Trait 供查询器 Query 使用。

我们先看看查询器类 Query:

  1. class Query
  2. {
  3. use Builder;
  4. public const MODEL_READ = 'read';
  5. public const MODEL_WRITE = 'write';
  6. private $transaction;
  7. public function __construct(ITransaction $transaction)
  8. {
  9. $this->transaction = $transaction;
  10. }
  11. /**
  12. * 开启事务
  13. */
  14. public function begin($model = 'write'): bool
  15. {
  16. return $this->transaction->begin($model);
  17. }
  18. /**
  19. * 提交事务
  20. */
  21. public function commit(): bool
  22. {
  23. return $this->transaction->commit();
  24. }
  25. /**
  26. * 回滚事务
  27. */
  28. public function rollback(): bool
  29. {
  30. return $this->transaction->rollback();
  31. }
  32. /**
  33. * 便捷方法:列表查询
  34. */
  35. public function list(): array
  36. {
  37. $list = $this->transaction->command(...$this->compile());
  38. if ($list === false) {
  39. throw new DBException($this->lastError(), $this->lastErrorNo());
  40. }
  41. return $list;
  42. }
  43. /**
  44. * 便捷方法:查询一行记录
  45. */
  46. public function one(): array
  47. {
  48. $list = $this->transaction->command(...$this->limit(1)->compile());
  49. if ($list === false) {
  50. throw new DBException($this->lastError(), $this->lastErrorNo());
  51. }
  52. if ($list) {
  53. return $list[0];
  54. }
  55. return [];
  56. }
  57. ...
  58. /**
  59. * 执行 SQL
  60. * 有两种方式:
  61. * 1. 调此方法时传入相关参数;
  62. * 2. 通过 Builder 提供的 Active Record 方法组装 SQL,调此方法(不传参数)执行并返回结果
  63. */
  64. public function execute(string $preSql = '', array $params = [])
  65. {
  66. if (!func_num_args()) {
  67. $result = $this->transaction->command(...$this->compile());
  68. } else {
  69. $result = $this->transaction->command(...$this->prepareSQL($preSql, $params));
  70. }
  71. if ($result === false) {
  72. throw new DBException($this->lastError(), $this->lastErrorNo());
  73. }
  74. return $result;
  75. }
  76. public function lastInsertId()
  77. {
  78. return $this->transaction->lastInsertId();
  79. }
  80. public function affectedRows()
  81. {
  82. return $this->transaction->affectedRows();
  83. }
  84. }

该入口类做了以下几件事情:

  • 提供 list()、one()、page()、execute() 等方法执行 SQL 语句,其内部是通过 transaction 实现的;
  • 通过 Builder 这个 Trait 对外提供 SQL 构造功能;
  • 委托 transaction 实现事务功能;

我们再简单看下 Builder 的实现:

  1. Trait Builder
  2. {
  3. ...
  4. public function select($fields = null)
  5. {
  6. if ($this->type) {
  7. return $this;
  8. }
  9. $this->type = 'select';
  10. $this->fields($fields);
  11. return $this;
  12. }
  13. /**
  14. * 预处理 SQL
  15. * @param string $sql 格式:select * from t_name where uid=:uid
  16. * @param array $params 格式:['uid' => $uid]
  17. * @return array 输出格式:sql: select * from t_name where uid=?,params: [$uid]
  18. * @throws \Exception
  19. */
  20. private function prepareSQL(string $sql, array $params)
  21. {
  22. $sql = trim($sql);
  23. if (!$params) {
  24. return [$sql, []];
  25. }
  26. preg_match_all('/:([^\s;]+)/', $sql, $matches);
  27. if (!($matches = $matches[1])) {
  28. return [$sql, []];
  29. }
  30. if (count($matches) !== count($params)) {
  31. throw new \Exception("SQL 占位数与参数个数不符。SQL:$sql,参数:" . print_r($params, true));
  32. }
  33. $p = [];
  34. foreach ($matches as $flag) {
  35. if (!array_key_exists($flag, $params)) {
  36. throw new \Exception("SQL 占位符与参数不符。SQL:$sql,参数:" . print_r($params, true));
  37. }
  38. $value = $params[$flag];
  39. if ($this->isExpression($value)) {
  40. $sql = preg_replace("/:$flag(?=\s|$)/", $value, $sql);
  41. } else {
  42. $p[] = $value;
  43. }
  44. }
  45. $sql = preg_replace('/:[-a-zA-Z0-9_]+/', '?', $sql);
  46. return [$sql, $p];
  47. }
  48. /**
  49. * 编译
  50. * 目前仅支持 select,update,insert,replace,delete
  51. * @param bool $reset 编译后是否重置构造器
  52. * @return array [$preSql, $params]
  53. */
  54. private function compile(bool $reset = true)
  55. {
  56. if (!$this->type) {
  57. return ['', []];
  58. }
  59. $method = 'compile' . ucfirst($this->type);
  60. if (method_exists($this, $method)) {
  61. $this->rawSqlInfo = $this->$method();
  62. if ($reset) {
  63. $this->reset();
  64. }
  65. return $this->rawSqlInfo;
  66. }
  67. return ['', []];
  68. }
  69. private function compileSelect()
  70. {
  71. $sql = "select $this->fields ";
  72. $params = [];
  73. if ($this->table) {
  74. $sql .= implode(
  75. ' ',
  76. array_filter([
  77. 'from',
  78. $this->table,
  79. $this->join,
  80. $this->where,
  81. $this->groupBy,
  82. $this->having,
  83. $this->orderBy,
  84. $this->limitStr()
  85. ])
  86. );
  87. $params = array_merge($this->joinParams, $this->whereParams, $this->havingParams);
  88. }
  89. return [$this->trimSpace($sql), $params];
  90. }
  91. ...
  92. /**
  93. * 条件(where、on、having 等)
  94. * 为了记忆和使用方便,目前只提供了最基本的一些形式,复杂的条件请使用原生写法
  95. * $conditions 数组格式:
  96. * // 基本的 and 查询
  97. * [
  98. * 'uid' => 232,
  99. * 'name' => '里斯',
  100. * 'b.age' => 34,
  101. * 'level_id' => [1,2,3], // in
  102. * 'count' => new Expression('count + 1'),
  103. * ]
  104. *
  105. * [
  106. * "(uid=:uid1 or uid=:uid2) and count=:count", // 原生预处理 SQL
  107. * ['uid1' => 12, 'uid2' => 13, 'count' => new Expression('count+1')]
  108. * ]
  109. * @param string|array $conditions
  110. * @return array [$preSql, $params],$preSql: 用 ? 占位的预处理 SQL
  111. * @throws \Exception
  112. */
  113. private function condition($conditions)
  114. {
  115. if (is_string($conditions)) {
  116. return [$conditions, []];
  117. }
  118. if (!$conditions || !is_array($conditions)) {
  119. return [];
  120. }
  121. if (is_int(key($conditions)) && count($conditions) <= 2) {
  122. if (count($conditions) == 1) {
  123. $conditions[1] = [];
  124. }
  125. return $this->prepareSQL($conditions[0], $conditions[1]);
  126. }
  127. $where = '1=1';
  128. $params = [];
  129. foreach ($conditions as $key => $condition) {
  130. $key = $this->plainText($key);
  131. if (is_array($condition)) {
  132. // in 查询
  133. $where .= " and $key in(" . implode(',', array_fill(0, count($condition), '?')) . ')';
  134. $params = array_merge($params, $condition);
  135. } else {
  136. // = 查询
  137. if ($this->isExpression($condition)) {
  138. $where .= " and $key = $condition";
  139. } else {
  140. $where .= " and $key = ?";
  141. $params[] = $condition;
  142. }
  143. }
  144. }
  145. return [str_replace('1=1 and ', '', $where), $params];
  146. }
  147. ...
  148. }

构造器主要提供和 SQL 子句对应的方法来构造和编译 SQL,并提供对原生 SQL 的支持。

该构造器并未对所有的 SQL 语句做方法上的实现(比如子查询),只对最常用的功能提供了支持,复杂的 SQL 建议直接写 SQL 语句(一些框架对复杂 SQL 构造也提供了方法级别的支持,但这其实会带来使用和维护上的复杂性,它导致 SQL 不够直观)。

完整的查询模块代码

事务

事务是集中管理 SQL 执行上下文的地方,所有的 SQL 都是在事务中执行的(没有调 begin() 则是隐式事务)。

我们的查询器是协程安全的,即一个 Query 实例可以在多个协程中并发执行事务而不会相互影响。协程安全性是通过事务模块保证的,这里需要处理两个维度的“事务”:数据库维度和协程维度。不但需要保证数据库事务的完整执行,还要保证多个协程间的 SQL 执行不会相互影响。

我们先看一个多协程并发执行事务的例子(在两个子协程中使用同一个 Query 实例执行事务:先从数据库查询用户信息,然后更新姓名):

  1. $query = new Query(...);
  2. for ($i = 0; $i < 2; $i++) {
  3. go(function () use ($query) {
  4. $query->begin();
  5. $user = $query->select("uid,name")->from("users")->where("phone=:phone", ["phone" => "13908987654"])->one();
  6. $query->update('users')->set(['name' => "李四"])->where("uid=:uid", ['uid' => $user['uid']])->execute();
  7. $query->commit();
  8. });
  9. }

上面代码执行步骤如图:

在上图两个协程不断切换过程中,各自的事务是在独立执行的,互不影响。

现实中,我们会在仓储中使用查询器,每个仓储持有一个查询器实例,而仓储是单例模式,多协程共享的,因而查询器也是多协程共享的。如下:

  1. /**
  2. * MySQL 仓储基类
  3. * 仓储是单例模式(通过容器实现单例),多协程会共享同一个仓储实例
  4. */
  5. abstract class MySQLRepository extends Repository implements ITransactional
  6. {
  7. /**
  8. * 查询器
  9. */
  10. protected $query;
  11. public function __construct()
  12. {
  13. if (!$this->dbAlias()) {
  14. throw new \Exception('dbName can not be null');
  15. }
  16. // 通过工厂创建查询器实例
  17. $this->query = MySQLFactory::build($this->dbAlias());
  18. }
  19. ...
  20. }

事务模块是如何实现协程并发事务的隔离性呢?我们用协程上下文 TContext 类实现协程间数据的隔离,事务类 CoTransaction 持有 TContext 实例,事务中所有的状态信息都通过 TContext 存取,以实现协程间状态数据互不影响。

我们先看看协程上下文类:

  1. class TContext implements \ArrayAccess
  2. {
  3. private $container = [];
  4. ...
  5. public function offsetGet($offset)
  6. {
  7. if (!isset($this->container[Co::getuid()])) {
  8. return null;
  9. }
  10. return $this->container[Co::getuid()][$offset] ?? null;
  11. }
  12. public function offsetSet($offset, $value)
  13. {
  14. $cuid = Co::getuid();
  15. if (!isset($this->container[$cuid])) {
  16. $this->init();
  17. }
  18. $this->container[$cuid][$offset] = $value;
  19. }
  20. private function init()
  21. {
  22. $this->container[Co::getuid()] = [];
  23. // 协程退出时需要清理当前协程上下文
  24. Co::defer(function () {
  25. unset($this->container[Co::getuid()]);
  26. });
  27. }
  28. }

协程上下文内部通过 $container 数组维护每个协程的数据。该类实现了 ArrayAccess 接口,可以通过下标访问,如:

  1. // 创建上下文实例
  2. $context = new TContext();
  3. // 设置当前协程的数据
  4. $context["model"] = "write";
  5. // 访问当前协程的数据
  6. $context["model"];

再看看事务。

事务接口定义:

  1. interface ITransaction
  2. {
  3. public function begin(string $model = 'write', bool $isImplicit = false): bool;
  4. /**
  5. * 发送 SQL 指令
  6. */
  7. public function command(string $preSql, array $params = []);
  8. /**
  9. * 提交事务
  10. * @param bool $isImplicit 是否隐式事务,隐式事务不会向 MySQL 提交 commit (要求数据库服务器开启了自动提交的配置)
  11. * @return bool
  12. * @throws \Exception
  13. */
  14. public function commit(bool $isImplicit = false): bool;
  15. public function rollback(): bool;
  16. /**
  17. * 获取或设置当前事务执行模式
  18. * @param string 读/写模式 read/write
  19. * @return string 当前事务执行模式
  20. */
  21. public function model(?string $model = null): string;
  22. ...
  23. /**
  24. * 获取一次事务中执行的 SQL 列表
  25. * @return array
  26. */
  27. public function sql():array;
  28. }

上面接口定义了事务管理器的主要工作:开启事务、执行 SQL、提交/回滚事务以及和本次事务执行相关的信息。

我们再来看看它的实现类 CoTransaction,该类是整个查询器中最重要的类,我们把整个类的代码完整贴出来:

  1. /**
  2. * 协程版事务管理器
  3. * 注意:事务开启直到提交/回滚的过程中会一直占用某个 IConnector 实例,如果有很多长事务,则会很快耗完连接池资源
  4. */
  5. class CoTransaction implements ITransaction
  6. {
  7. private $pool;
  8. // 事务的所有状态信息(运行状态、SQL、运行模式、运行结果等)都是存储在上下文中
  9. private $context;
  10. /**
  11. * 创建事务实例时需要提供连接池,并在内部创建该事物的协程上下文实例
  12. */
  13. public function __construct(IPool $pool)
  14. {
  15. $this->pool = $pool;
  16. $this->context = new TContext();
  17. }
  18. public function __destruct()
  19. {
  20. // 如果事务没有结束,则回滚
  21. if ($this->isRunning()) {
  22. $this->rollback();
  23. }
  24. }
  25. /**
  26. * 开启事务
  27. */
  28. public function begin(string $model = 'write', bool $isImplicit = false): bool
  29. {
  30. // 如果事务已经开启了,则直接返回
  31. if ($this->isRunning()) {
  32. return true;
  33. }
  34. // 事务模式(决定从读连接池还是写连接池拿连接对象)
  35. $this->model($model);
  36. // 设置事务运行状态
  37. $this->isRunning(true);
  38. // 获取数据库连接
  39. try {
  40. if (!($connector = $this->connector())) {
  41. throw new ConnectException("获取连接失败");
  42. }
  43. } catch (\Exception $exception) {
  44. $this->isRunning(false);
  45. throw new TransactionException($exception->getMessage(), $exception->getCode());
  46. }
  47. // 开启新事务前,需要清除上一次事务的数据
  48. $this->resetLastExecInfo();
  49. $this->clearSQL();
  50. // 调用数据库连接对象的 begin 方法开始事务(如果是隐式事务则不调用)
  51. return $isImplicit || $connector->begin();
  52. }
  53. /**
  54. * 执行 SQL 指令
  55. * 如果是隐式事务,则在该方法中自动调用 begin 和 commit 方法
  56. */
  57. public function command(string $preSql, array $params = [])
  58. {
  59. if (!$preSql) {
  60. return false;
  61. }
  62. // 是否隐式事务:外界没有调用 begin 而是直接调用 command 则为隐式事务
  63. $isImplicit = !$this->isRunning();
  64. // 如果是隐式事务,则需要自动开启事务
  65. if ($isImplicit && !$this->begin($this->calcModelFromSQL($preSql), true)) {
  66. return false;
  67. }
  68. // 执行 SQL
  69. $result = $this->exec([$preSql, $params]);
  70. // 隐式事务需要及时提交
  71. if ($isImplicit && !$this->commit($isImplicit)) {
  72. return false;
  73. }
  74. return $result;
  75. }
  76. /**
  77. * 提交事务
  78. */
  79. public function commit(bool $isImplicit = false): bool
  80. {
  81. if (!$this->isRunning()) {
  82. return true;
  83. }
  84. $result = true;
  85. if (!$isImplicit) {
  86. // 显式事务才需要真正提交到 MySQL 服务器
  87. if ($conn = $this->connector(false)) {
  88. $result = $conn->commit();
  89. if ($result === false) {
  90. // 执行失败,试图回滚
  91. $this->rollback();
  92. return false;
  93. }
  94. } else {
  95. return false;
  96. }
  97. }
  98. // 释放事务占用的资源
  99. $this->releaseTransResource();
  100. return $result;
  101. }
  102. /**
  103. * 回滚事务
  104. * 无论是提交还是回滚,都需要释放本次事务占用的资源
  105. */
  106. public function rollback(): bool
  107. {
  108. if (!$this->isRunning()) {
  109. return true;
  110. }
  111. if ($conn = $this->connector(false)) {
  112. $conn->rollback();
  113. }
  114. $this->releaseTransResource();
  115. return true;
  116. }
  117. /**
  118. * 获取或设置当前事务执行模式
  119. */
  120. public function model(?string $model = null): string
  121. {
  122. // 事务处于开启状态时不允许切换运行模式
  123. if (!isset($model) || $this->isRunning()) {
  124. return $this->context['model'];
  125. }
  126. $this->context['model'] = $model === 'read' ? 'read' : 'write';
  127. return $model;
  128. }
  129. public function lastInsertId()
  130. {
  131. return $this->getLastExecInfo('insert_id');
  132. }
  133. public function affectedRows()
  134. {
  135. return $this->getLastExecInfo('affected_rows');
  136. }
  137. public function lastError()
  138. {
  139. return $this->getLastExecInfo('error');
  140. }
  141. public function lastErrorNo()
  142. {
  143. return $this->getLastExecInfo('error_no');
  144. }
  145. /**
  146. * 本次事务执行的所有 SQL
  147. * 该版本并没有做记录
  148. */
  149. public function sql(): array
  150. {
  151. return $this->context['sql'] ?? [];
  152. }
  153. /**
  154. * 释放当前事务占用的资源
  155. */
  156. private function releaseTransResource()
  157. {
  158. // 保存本次事务相关执行结果供外界查询使用
  159. $this->saveLastExecInfo();
  160. // 归还连接资源
  161. $this->giveBackConnector();
  162. unset($this->context['model']);
  163. $this->isRunning(false);
  164. }
  165. /**
  166. * 保存事务最终执行的一些信息
  167. */
  168. private function saveLastExecInfo()
  169. {
  170. if ($conn = $this->connector(false)) {
  171. $this->context['last_exec_info'] = [
  172. 'insert_id' => $conn->insertId(),
  173. 'error' => $conn->lastError(),
  174. 'error_no' => $conn->lastErrorNo(),
  175. 'affected_rows' => $conn->affectedRows(),
  176. ];
  177. } else {
  178. $this->context['last_exec_info'] = [];
  179. }
  180. }
  181. private function resetLastExecInfo()
  182. {
  183. unset($this->context['last_exec_info']);
  184. }
  185. private function getLastExecInfo(string $key)
  186. {
  187. return isset($this->context['last_exec_info']) ? $this->context['last_exec_info'][$key] : '';
  188. }
  189. /**
  190. * 执行指令池中的指令
  191. * @param $sqlInfo
  192. * @return mixed
  193. * @throws
  194. */
  195. private function exec(array $sqlInfo)
  196. {
  197. if (!$sqlInfo || !$this->isRunning()) {
  198. return true;
  199. }
  200. return $this->connector()->query($sqlInfo[0], $sqlInfo[1]);
  201. }
  202. private function clearSQL()
  203. {
  204. unset($this->context['sql']);
  205. }
  206. private function calcModelFromSQL(string $sql): string
  207. {
  208. if (preg_match('/^(update|replace|delete|insert|drop|grant|truncate|alter|create)\s/i', trim($sql))) {
  209. return 'write';
  210. }
  211. return 'read';
  212. }
  213. /**
  214. * 获取连接资源
  215. */
  216. private function connector(bool $usePool = true)
  217. {
  218. if ($connector = $this->context['connector']) {
  219. return $connector;
  220. }
  221. if (!$usePool) {
  222. return null;
  223. }
  224. $this->context['connector'] = $this->pool->getConnector($this->model());
  225. return $this->context['connector'];
  226. }
  227. /**
  228. * 归还连接资源
  229. */
  230. private function giveBackConnector()
  231. {
  232. if ($this->context['connector']) {
  233. $this->pool->pushConnector($this->context['connector']);
  234. }
  235. unset($this->context['connector']);
  236. }
  237. private function isRunning(?bool $val = null)
  238. {
  239. if (isset($val)) {
  240. $this->context['is_running'] = $val;
  241. } else {
  242. return $this->context['is_running'] ?? false;
  243. }
  244. }
  245. }

该类中,一次 SQL 执行(无论是显式事务还是隐式事务)的步骤:

begin -> exec -> commit/rollback

  1. begin:

    • 判断是否可开启新事务(如果已有事务在运行,则不可开启);
    • 设置事务执行模式(read/write);
    • 将当前事务状态设置为 running;
    • 获取连接对象;
    • 清理本事务实例中上次事务的痕迹(上下文、SQL);
    • 调连接对象的 begin 启动数据库事务;
  2. exec:
    • 调用连接对象的 query 方法执行 SQL(prepare 模式);
  3. commit:
    • 判断当前状态是否可提交(running 状态才可以提交);
    • 调用连接对象的 commit 方法提交数据库事务(如果失败则走回滚);
    • 释放本次事务占用的资源(保存本次事务执行的相关信息、归还连接对象、清除上下文里面相关信息)
  4. rollback:
    • 判断当前状态是否可回滚;
    • 调用连接对象的 rollback 回滚数据库事务;
    • 释放本次事务占用的资源(同上);

优化:

CoTransaction 依赖 IPool 连接池,这种设计并不合理(违反了迪米特法则)。从逻辑上说,事务管理类真正依赖的是连接对象,而非连接池对象,因而事务模块应该依赖连接模块而不是连接池模块。让事务管理类依赖连接池,一方面向事务模块暴露了连接管理的细节, 另一方面意味着如果使用该事务管理类,就必须使用连接池技术。

一种优化方案是,在连接模块提供一个连接管理类供外部(事务模块)取还连接:

  1. interface IConnectorManager
  2. {
  3. public function getConnector() IConnector;
  4. public function giveBackConnector(IConnector $conn);
  5. }

IConnectorManager 注入到 CoTransaction 中:

  1. class CoTransaction implements ITransaction
  2. {
  3. ...
  4. public function __construct(IConnectorManager $connMgr)
  5. {
  6. ...
  7. }
  8. }

连接管理器 IConnectorManager 承担了工厂方法角色,至此,事务模块仅依赖连接模块,而不用依赖连接池。

连接池

连接池模块由 IPool 接口和 CoPool 实现类组成。

连接池模块和连接模块之间的关系比较巧妙(上面优化后的方案)。从高层(接口层面)来说,连接池模块依赖连接模块:连接池操作(取还)IConnector 的实例;从实现上来说,连接模块同时又依赖连接池模块:PoolConnectorManager(使用连接池技术的连接管理器)依赖连接池模块来操作连接对象(由于该依赖是实现层面的而非接口层面,因而它不是必然的,如果连接管理器不使用连接池技术则不需要依赖连接池模块)。“连接管理器”这个角色很重要:它对外(事务模块)屏蔽了连接池模块的存在,代价是在内部引入了对连接池模块的依赖(也就是用内部依赖换外部依赖)。

经过上面的分析我们得出,连接池模块和连接模块具有较强的耦合性,连接模块可以对外屏蔽掉连接池模块的存在,因而在设计上我们可以将这两个模块看成一个大模块放在一个目录下面,在该目录下再细分成两个内部模块即可。

我们先看看连接池接口。

  1. interface IPool
  2. {
  3. /**
  4. * 从连接池中获取连接对象
  5. */
  6. public function getConnector(string $type = 'write'): IConnector;
  7. /**
  8. * 归还连接
  9. */
  10. public function pushConnector(IConnector $connector): bool;
  11. /**
  12. * 连接池中连接数
  13. * @return array ['read' => 3, 'write' => 3]
  14. */
  15. public function count(): array;
  16. /**
  17. * 关闭连接池
  18. */
  19. public function close(): bool;
  20. }

从上面接口定义我们发现,该连接池并非通用连接池,而是针对数据库连接做的定制(count() 方法返回的数据里面有 read、write,它暴露了一个细节:该连接池内部维护了读写两种连接池)。此设计也透露出该模块和连接模块的强耦合性。

实现类 CoPool 稍显复杂,我们贴出代码:

  1. class CoPool implements IPool
  2. {
  3. ...
  4. protected static $container = [];
  5. protected $readPool;
  6. protected $writePool;
  7. // 数据库连接生成器,连接池使用此生成器创建连接对象
  8. protected $connectorBuilder;
  9. // 连接池大小
  10. protected $size;
  11. // 记录每个连接的相关信息
  12. protected $connectsInfo = [];
  13. // 当前存活的连接数(包括不在池中的)
  14. protected $connectNum;
  15. // 读连接数
  16. protected $readConnectNum;
  17. // 写连接数
  18. protected $writeConnectNum;
  19. protected $maxSleepTime;
  20. protected $maxExecCount;
  21. protected $status;
  22. // 连续等待连接对象失败次数(一般是长事务导致某次事务处理长时间占用连接资源)
  23. protected $waitTimeoutNum;
  24. protected function __construct(IConnectorBuilder $connectorBuilder, int $size = 25, int $maxSleepTime = 600, int $maxExecCount = 1000)
  25. {
  26. // 创建读写 Channel
  27. $this->readPool = new co\Channel($size);
  28. $this->writePool = new co\Channel($size);
  29. ...
  30. }
  31. /**
  32. * 单例
  33. * 实际是伪单例
  34. */
  35. public static function instance(IConnectorBuilder $connectorBuilder, int $size = 25, int $maxSleepTime = 600, int $maxExecCount = 1000): CoPool
  36. {
  37. // 同一个连接生成器创建的连接对象由同一个连接池管理
  38. if (!isset(static::$container[$connectorBuilder->getKey()])) {
  39. static::$container[$connectorBuilder->getKey()] = new static($connectorBuilder, $size, $maxSleepTime, $maxExecCount);
  40. }
  41. return static::$container[$connectorBuilder->getKey()];
  42. }
  43. /**
  44. * 从连接池中获取 MySQL 连接对象
  45. */
  46. public function getConnector(string $type = 'write'): IConnector
  47. {
  48. if (!$this->isOk()) {
  49. throw new PoolClosedException("连接池已经关闭,无法获取连接");
  50. }
  51. // 根据读写模式选择是使用读连接池还是写连接池
  52. $pool = $this->getPool($type);
  53. // 连接池是空的,试图创建连接
  54. if ($pool->isEmpty()) {
  55. // 超额,不能再创建,需等待
  56. // 此处试图创建的数量大于连接池真正大小,是为了应对高峰期等异常情况。归还的时候多创建出来的会直接被关闭掉(随建随销)
  57. if (($type == 'read' ? $this->readConnectNum : $this->writeConnectNum) > $this->size * 6) {
  58. // 多次等待失败,则直接返回
  59. // 优化点:这里面没有针对读写池分别计数
  60. if ($this->waitTimeoutNum > self::MAX_WAIT_TIMEOUT_NUM) {
  61. // 超出了等待失败次数限制,直接抛异常
  62. throw new ConnectFatalException("多次获取连接超时,请检查数据库服务器状态");
  63. }
  64. // 等待连接归还
  65. $conn = $pool->pop(4);
  66. // 等待失败
  67. if (!$conn) {
  68. switch ($pool->errCode) {
  69. case SWOOLE_CHANNEL_TIMEOUT:
  70. // 优化:要区分读池子超时还是写池子超时
  71. $this->waitTimeoutNum++;
  72. $errMsg = "获取连接超时";
  73. break;
  74. case SWOOLE_CHANNEL_CLOSED:
  75. $errMsg = "获取连接失败:连接池已关闭";
  76. break;
  77. default:
  78. $errMsg = "获取连接失败";
  79. break;
  80. }
  81. throw new ConnectException($errMsg);
  82. }
  83. } else {
  84. try {
  85. // 创建新连接
  86. $conn = $this->createConnector($type);
  87. } catch (ConnectException $exception) {
  88. if ($exception->getCode() == 1040) {
  89. // 连接数据库时失败:Too many connections,此时需要等待被占用的连接归还
  90. // 这里可以优化下:先判断下该连接池有无在维护的连接,有的话才等待
  91. $conn = $pool->pop(4);
  92. }
  93. if (!$conn) {
  94. // 等待连接超时,记录超时次数
  95. if ($pool->errCode == SWOOLE_CHANNEL_TIMEOUT) {
  96. $this->waitTimeoutNum++;
  97. }
  98. throw new ConnectException($exception->getMessage(), $exception->getCode());
  99. }
  100. }
  101. }
  102. } else {
  103. // 从连接池获取
  104. $conn = $pool->pop(1);
  105. }
  106. // 变更该连接的状态信息
  107. $connectInfo = $this->connectInfo($conn);
  108. $connectInfo->popTime = time();
  109. $connectInfo->status = ConnectorInfo::STATUS_BUSY;
  110. // 成功拿到连接,将等待次数清零
  111. $this->waitTimeoutNum = 0;
  112. return $conn;
  113. }
  114. /**
  115. * 归还连接
  116. * @param IConnector $connector
  117. * @return bool
  118. */
  119. public function pushConnector(IConnector $connector): bool
  120. {
  121. if (!$connector) {
  122. return true;
  123. }
  124. $connInfo = $this->connectInfo($connector);
  125. $pool = $this->getPool($connInfo->type);
  126. // 如果连接池有问题(如已关闭)、满了、连接有问题,则直接关闭
  127. if (!$this->isOk() || $pool->isFull() || !$this->isHealthy($connector)) {
  128. return $this->closeConnector($connector);
  129. }
  130. // 变更连接状态
  131. if ($connInfo) {
  132. $connInfo->status = ConnectorInfo::STATUS_IDLE;
  133. $connInfo->pushTime = time();
  134. }
  135. return $pool->push($connector);
  136. }
  137. /**
  138. * 关闭连接池
  139. * @return bool
  140. */
  141. public function close(): bool
  142. {
  143. $this->status = self::STATUS_CLOSED;
  144. // 关闭通道中所有的连接。等待5ms为的是防止还有等待push的排队协程
  145. while ($conn = $this->readPool->pop(0.005)) {
  146. $this->closeConnector($conn);
  147. }
  148. while ($conn = $this->writePool->pop(0.005)) {
  149. $this->closeConnector($conn);
  150. }
  151. // 关闭通道
  152. $this->readPool->close();
  153. $this->writePool->close();
  154. return true;
  155. }
  156. public function count(): array
  157. {
  158. return [
  159. 'read' => $this->readPool->length(),
  160. 'write' => $this->writePool->length()
  161. ];
  162. }
  163. protected function closeConnector(IConnector $connector)
  164. {
  165. if (!$connector) {
  166. return true;
  167. }
  168. $objId = $this->getObjectId($connector);
  169. // 关闭连接
  170. $connector->close();
  171. // 处理计数
  172. $this->untickConnectNum($this->connectsInfo[$objId]->type);
  173. // 删除统计信息
  174. unset($this->connectsInfo[$objId]);
  175. return true;
  176. }
  177. protected function isOk()
  178. {
  179. return $this->status == self::STATUS_OK;
  180. }
  181. protected function getPool($type = 'write'): co\Channel
  182. {
  183. if (!$type || !in_array($type, ['read', 'write'])) {
  184. $type = 'write';
  185. }
  186. return $type === 'write' ? $this->writePool : $this->readPool;
  187. }
  188. /**
  189. * 创建新连接对象
  190. * @param string $type
  191. * @return IConnector
  192. * @throws \Dev\MySQL\Exception\ConnectException
  193. */
  194. protected function createConnector($type = 'write'): IConnector
  195. {
  196. $conn = $this->connectorBuilder->build($type);
  197. if ($conn) {
  198. // 要在 connect 前 tick(计数),否则无法阻止高并发协程打入(因为 connect 会造成本协程控制权让出,此时本次计数还没有增加)
  199. $this->tickConnectNum($type);
  200. try {
  201. $conn->connect();
  202. } catch (ConnectException $exception) {
  203. // 撤销 tick
  204. $this->untickConnectNum($type);
  205. throw new ConnectException($exception->getMessage(), $exception->getCode());
  206. }
  207. // 创建本连接的统计信息实例
  208. $this->connectsInfo[$this->getObjectId($conn)] = new ConnectorInfo($conn, $type);
  209. }
  210. return $conn;
  211. }
  212. protected function tickConnectNum(string $type)
  213. {
  214. $this->changeConnectNum($type, 1);
  215. }
  216. protected function untickConnectNum(string $type)
  217. {
  218. $this->changeConnectNum($type, -1);
  219. }
  220. private function changeConnectNum(string $type, $num)
  221. {
  222. $this->connectNum = $this->connectNum + $num;
  223. if ($type == 'read') {
  224. $this->readConnectNum = $this->readConnectNum + $num;
  225. } else {
  226. $this->writeConnectNum = $this->writeConnectNum + $num;
  227. }
  228. }
  229. /**
  230. * 检查连接对象的健康情况,以下情况视为不健康:
  231. * 1. SQL 执行次数超过阈值;
  232. * 2. 连接对象距最后使用时间超过阈值;
  233. * 3. 连接对象不是连接池创建的
  234. * @param IConnector $connector
  235. * @return bool
  236. */
  237. protected function isHealthy(IConnector $connector): bool
  238. {
  239. $connectorInfo = $this->connectInfo($connector);
  240. if (!$connectorInfo) {
  241. return false;
  242. }
  243. // 如果连接处于忙态(一般是还处于事务未提交状态),则一律返回 ok
  244. if ($connectorInfo->status === ConnectorInfo::STATUS_BUSY) {
  245. return true;
  246. }
  247. if (
  248. $connectorInfo->execCount() >= $this->maxExecCount ||
  249. time() - $connectorInfo->lastExecTime() >= $this->maxSleepTime
  250. ) {
  251. return false;
  252. }
  253. return true;
  254. }
  255. protected function connectInfo(IConnector $connector): ConnectorInfo
  256. {
  257. return $this->connectsInfo[$this->getObjectId($connector)];
  258. }
  259. protected function getObjectId($object): string
  260. {
  261. return spl_object_hash($object);
  262. }
  263. }

这里有几点需要注意:

  1. 连接池使用的是伪单例模式,同一个生成器对应的是同一个连接池实例;
  2. 连接池内部维护了读写两个池子,生成器生成的读写连接对象分别放入对应的池子里面;
  3. 从连接池取连接对象的时候,如果连接池为空,则根据情况决定是创建新连接还是等待。此处并非是在池子满了的情况下就等待,而是会超额创建,为的是应对峰值等异常情况。当然一个优化点是,将溢出比例做成可配置的,由具体的项目决定溢出多少。另外,如果创建新连接的时候数据库服务器报连接过多的错误,也需要转为等待连接归还;
  4. 如果多次等待连接失败(超时),则后面的请求会直接抛出异常(直到池子不为空)。这里有个优化点:目前的实现没有区分是读池子超时还是写池子超时;
  5. 归还连接时,如果池子满了,或者连接寿命到期了,则直接关闭连接;

后面在连接模块会讲解连接生成器,到时我们会知道一个连接池实例到底维护的是哪些连接对象。

连接

连接模块负责和数据库建立连接并发出 SQL 请求,其底层使用 Swoole 的 MySQL 驱动。连接模块由连接对象连接生成器构成,对外暴露 IConnectorIConnectorBuilder 接口。

(在我们的优化版本中,一方面引入了连接管理器 IConnectorManager,另一方面将连接模块连接池模块合并成一个大模块,因而整个连接模块对外暴露的是 IConnectorManagerIConnector 两个接口。)

连接对象的实现比较简单,我们重点看下 CoConnector 里面查询的处理:

  1. class CoConnector implements IConnector
  2. {
  3. ...
  4. public function __destruct()
  5. {
  6. $this->close();
  7. }
  8. public function connect(): bool
  9. {
  10. if ($this->mysql->connected) {
  11. return true;
  12. }
  13. $conn = $this->mysql->connect($this->config);
  14. if (!$conn) {
  15. throw new ConnectException($this->mysql->connect_error, $this->mysql->connect_errno);
  16. }
  17. return $conn;
  18. }
  19. /**
  20. * 执行 SQL 语句
  21. */
  22. public function query(string $sql, array $params = [], int $timeout = 180)
  23. {
  24. $prepare = $params ? true : false;
  25. $this->execCount++;
  26. $this->lastExecTime = time();
  27. // 是否要走 prepare 模式
  28. if ($prepare) {
  29. $statement = $this->mysql->prepare($sql, $timeout);
  30. // 失败,尝试重新连接数据库
  31. if ($statement === false && $this->tryReconnectForQueryFail()) {
  32. $statement = $this->mysql->prepare($sql, $timeout);
  33. }
  34. if ($statement === false) {
  35. $result = false;
  36. goto done;
  37. }
  38. // execute
  39. $result = $statement->execute($params, $timeout);
  40. // 失败,尝试重新连接数据库
  41. if ($result === false && $this->tryReconnectForQueryFail()) {
  42. $result = $statement->execute($params, $timeout);
  43. }
  44. } else {
  45. $result = $this->mysql->query($sql, $timeout);
  46. // 失败,尝试重新连接数据库
  47. if ($result === false && $this->tryReconnectForQueryFail()) {
  48. $result = $this->mysql->query($sql, $timeout);
  49. }
  50. }
  51. done:
  52. $this->lastExpendTime = time() - $this->lastExecTime;
  53. $this->peakExpendTime = max($this->lastExpendTime, $this->peakExpendTime);
  54. return $result;
  55. }
  56. ...
  57. /**
  58. * 失败重连
  59. */
  60. private function tryReconnectForQueryFail()
  61. {
  62. if ($this->mysql->connected || !in_array($this->mysql->errno, [2006, 2013])) {
  63. return false;
  64. }
  65. // 尝试重新连接
  66. $connRst = $this->connect();
  67. if ($connRst) {
  68. // 连接成功,需要重置以下错误(swoole 在重连成功后并没有重置这些属性)
  69. $this->mysql->error = '';
  70. $this->mysql->errno = 0;
  71. $this->mysql->connect_error = '';
  72. $this->mysql->connect_errno = 0;
  73. }
  74. return $connRst;
  75. }
  76. ...
  77. }

这里重点关注下查询的时候断线重连机制:先尝试执行 SQL,如果返回连接失败,则尝试重新连接。

我们再看看连接生成器:

  1. class CoConnectorBuilder implements IConnectorBuilder
  2. {
  3. protected static $container = [];
  4. protected $writeConfig;
  5. protected $readConfigs;
  6. protected $key;
  7. /**
  8. * 创建生成器的时候需要提供读写连接配置,其中读配置是一个数组(可以有多个读连接)
  9. */
  10. protected function __construct(DBConfig $writeConfig = null, array $readConfigs = [])
  11. {
  12. $this->writeConfig = $writeConfig;
  13. $this->readConfigs = $readConfigs;
  14. }
  15. /**
  16. * 这里采用伪单例:同样的读写配置使用同一个生成器
  17. */
  18. public static function instance(DBConfig $writeConfig = null, array $readConfigs = []): CoConnectorBuilder
  19. {
  20. if ($writeConfig && !$readConfigs) {
  21. $readConfigs = [$writeConfig];
  22. }
  23. $key = self::calcKey($writeConfig, $readConfigs);
  24. if (!isset(self::$container[$key])) {
  25. $builder = new static($writeConfig, $readConfigs);
  26. $builder->key = $key;
  27. self::$container[$key] = $builder;
  28. }
  29. return self::$container[$key];
  30. }
  31. /**
  32. * 创建并返回 IConnector 对象
  33. * @param string $connType read/write
  34. * @return IConnector
  35. */
  36. public function build(string $connType = 'write'): IConnector
  37. {
  38. /** @var DBConfig */
  39. $config = $connType == 'read' ? $this->getReadConfig() : $this->writeConfig;
  40. if (!($config instanceof DBConfig)) {
  41. return null;
  42. }
  43. return new CoConnector($config->host, $config->user, $config->password, $config->database, $config->port, $config->timeout, $config->charset);
  44. }
  45. public function getKey(): string
  46. {
  47. return $this->key;
  48. }
  49. private function getReadConfig()
  50. {
  51. return $this->readConfigs[mt_rand(0, count($this->readConfigs) - 1)];
  52. }
  53. /**
  54. * 根据配置计算 key,完全相同的配置对应同样的 key
  55. */
  56. private static function calcKey(DBConfig $writeConfig = null, array $readConfigs = []): string
  57. {
  58. $joinStr = function ($conf)
  59. {
  60. $arr = [
  61. $conf->host,
  62. $conf->port,
  63. $conf->user,
  64. $conf->password,
  65. $conf->database,
  66. $conf->charset,
  67. $conf->timeout,
  68. ];
  69. sort($arr);
  70. return implode('-', $arr);
  71. };
  72. $readArr = [];
  73. foreach ($readConfigs as $readConfig) {
  74. $readArr[] = $joinStr($readConfig);
  75. }
  76. sort($readArr);
  77. return md5($joinStr($writeConfig) . implode('$', $readArr));
  78. }
  79. }

该生成器是针对一主多从数据库架构的(包括未走读写分离的),如果使用是是其他数据库架构(如多主架构),则创建其他生成器即可。

同一套读写配置使用同一个生成器,对应的连接池也是同一个。

DBConfig 是一个 DTO 对象,不再阐述。

查询器的组装

使用工厂组装查询器实例:

  1. class MySQLFactory
  2. {
  3. /**
  4. * @param string $dbAlias 数据库配置别名,对应配置文件中数据库配置的 key
  5. */
  6. public static function build(string $dbAlias): Query
  7. {
  8. // 从配置文件获取数据库配置
  9. $dbConf = Config::getInstance()->getConf("mysql.$dbAlias");
  10. if (!$dbConf) {
  11. throw new ConfigNotFoundException("mysql." . $dbAlias);
  12. }
  13. if (!isset($dbConf['read']) && !isset($dbConf['write'])) {
  14. $writeConf = $dbConf;
  15. $readConfs = [$writeConf];
  16. } else {
  17. $writeConf = $dbConf['write'] ?? [];
  18. $readConfs = $dbConf['read'] ?? [$writeConf];
  19. }
  20. $writeConfObj = self::createConfObj($writeConf);
  21. $readConfObjs = [];
  22. foreach ($readConfs as $readConf) {
  23. $readConfObjs[] = self::createConfObj($readConf);
  24. }
  25. // 创建生成器、连接池、事务管理器
  26. // 在优化后版本中,用连接管理器代替连接池的位置即可
  27. $mySQLBuilder = CoConnectorBuilder::instance($writeConfObj, $readConfObjs);
  28. $pool = CoPool::instance($mySQLBuilder, $dbConf['pool']['size'] ?? 30);
  29. $transaction = new CoTransaction($pool);
  30. return new Query($transaction);
  31. }
  32. private static function createConfObj(array $config): DBConfig
  33. {
  34. if (!$config) {
  35. throw new Exception("config is null");
  36. }
  37. return new DBConfig(
  38. $config['host'],
  39. $config['user'],
  40. $config['password'],
  41. $config['database'],
  42. $config['port'] ?? 3306,
  43. $config['timeout'] ?? 3,
  44. $config['charset'] ?? 'utf8'
  45. );
  46. }
  47. }

至此,整个查询器的编写、创建和使用就完成了。

总结

  1. 项目的开发需要划分模块,模块之间尽量减少耦合,通过接口通信(模块之间依赖接口而不是实现);
  2. 如果两个模块之间具有强耦合性,则往往意味着两者本身应该归并到同一个模块中,在其内部划分子模块,对外屏蔽内部细节,如本项目的连接模块和连接池模块;
  3. 如果模块之间存在不合常理的依赖关系,则意味着模块划分有问题,如本项目中的事务模块依赖连接池模块;
  4. 有问题的模块划分往往违反第一点(也就是迪米特法则),会造成模块暴露细节、过多的依赖关系,影响设计的灵活性、可扩展性,如本项目中事务模块依赖连接池模块(虽然是实现层面的依赖而非接口层面),造成要使用 CoTransaction 时必须同时使用连接池;
  5. 编写生产可用的项目时需要注意处理异常场景,如本项目中从连接池获取连接对象,以及在连接对象上执行 SQL 时的断线重连;
  6. 设计本身是迭代式的,并非一蹴而就、一次性设计即可完成的,本项目在开发过程中已经经历过几次小重构,在本次分析时仍然发现一些设计上的缺陷。重构属于项目开发的一部分;

优化版 UML 图:

Swoole 实战:MySQL 查询器的实现(协程连接池版)的更多相关文章

  1. 分析easyswoole3.0源码,协程连接池(五)

    连接池的含义,很多都知道,比如mysql的数据库连接是有限的,一开始连接mysql创建N个连接,放到一个容器里,每次有请求去容器中取出,取出用完再放回去. es3demo里,有mysql的连接池. E ...

  2. PHP下的异步尝试三:协程的PHP版thunkify自动执行器

    PHP下的异步尝试系列 如果你还不太了解PHP下的生成器和协程,你可以根据下面目录翻阅 PHP下的异步尝试一:初识生成器 PHP下的异步尝试二:初识协程 PHP下的异步尝试三:协程的PHP版thunk ...

  3. swoole组件----mysql查询,插入数据

    注意!任何swoole函数都应该包含在go(function(){}) 经典查询方法query() go(function (){ $swoole_mysql = new Swoole\Corouti ...

  4. python装饰器,迭代器,生成器,协程

    python装饰器[1] 首先先明白以下两点 #嵌套函数 def out1(): def inner1(): print(1234) inner1()#当没有加入inner时out()不会打印输出12 ...

  5. 阿里云服务器实战(一) : 在Linux下Tomcat7下使用连接池

    云服务器 的环境如下: Tomcat7+MySql5.6 一,如果自定义了程序的文件目录 , 下面的/alidata/xxx 就是自定义的目录 在Linux的Tomcat的server.xml里的Ho ...

  6. python中socket、进程、线程、协程、池的创建方式和应用场景

    进程 场景 利用多核.高计算型的程序.启动数量有限 进程是计算机中最小的资源分配单位 进程和线程是包含关系 每个进程中都至少有一条线程 可以利用多核,数据隔离 创建 销毁 切换 时间开销都比较大 随着 ...

  7. [转]向facebook学习,通过协程实现mysql查询的异步化

    FROM : 通过协程实现mysql查询的异步化 前言 最近学习了赵海平的演讲,了解到facebook的mysql查询可以进行异步化,从而提高性能.由于facebook实现的比较早,他们不得不对php ...

  8. swoole与php协程实现异步非阻塞IO开发

    “协程可以在遇到阻塞的时候中断主动让渡资源,调度程序选择其他的协程运行.从而实现非阻塞IO” 然而php是不支持原生协程的,遇到阻塞时如不交由异步进程来执行是没有任何意义的,代码还是同步执行的,如下所 ...

  9. Swoole协程与传统fpm同步模式比较

    如果说数组是 PHP 的精髓,数组玩得不6的,根本不能算是会用PHP.那协程对于 Swoole 也是同理,不理解协程去用 Swoole,那就是在瞎用. 首先,Swoole 只能运行在命令行(Cli)模 ...

随机推荐

  1. SpringMVC知识大览

    SpringMVC大览 springMVC的基础知识 什么是SpringMVC? springmvc框架原理(掌握) 前端控制器.'处理映射器.处理适配器.视图解析器 springmvc的入门程序 目 ...

  2. 新建基于STM32F103ZET6的工程-HAL库版本

    1.STM32F103ZET6简介 STM32F103ZET6的FLASH容量为512K,64K的SRAM.按照STM32芯片的容量产品划分,STM32F103ZET6属于大容量的芯片. 2.下载HA ...

  3. MTK Android Driver :Battery电池曲线

    MTK Android Driver :battery电池曲线 1.配置文件位置: CUSTOM_KERNEL_BATTERY= battery mediatek\custom\\kernel\bat ...

  4. Genetic CNN: 经典NAS算法,遗传算法的标准套用 | ICCV 2017

    论文将标准的遗传算法应用到神经网络结构搜索中,首先对网络进行编码表示,然后进行遗传操作,整体方法十分简洁,搜索空间设计的十分简单,基本相当于只搜索节点间的连接方式,但是效果还是挺不错的,十分值得学习 ...

  5. Tcl编程第三天,数学运算

    1.tcl语言没有自己的数学计算,如果想要使用数学公式,必须得用C语言的库.使用方法如下. #!/usr/bin/tclsh set value [expr 8/5] puts $value set ...

  6. intelij idea 和 eclipse 使用上的区别

    一.项目创建区别 使用基于IntelliJ的IDE,都会对project和module的关系比较糊涂.用简单的一句话来概括是: IntelliJ系中的Project相当于Eclipse系中的works ...

  7. 动态网页D-html

    BOM(Browser Object Model)浏览器对象模型 window对象(window – 代表浏览器中打开的一个窗口) 1.alert()方法 – 定义一个消息对话框 window.ale ...

  8. 【spring 国际化】springMVC、springboot国际化处理详解

    在web开发中我们常常会遇到国际化语言处理问题,那么如何来做到国际化呢? 你能get的知识点? 使用springgmvc与thymeleaf进行国际化处理. 使用springgmvc与jsp进行国际化 ...

  9. 基于 HTML5 WebGL 的 CPU 监控系统

    前言 科技改变生活,科技的发展带来了生活方式的巨大改变.随着通信技术的不断演进,5G 技术应运而生,随时随地万物互联的时代已经来临.5G 技术不仅带来了更快的连接速度和前所未有的用户体验,也为制造业, ...

  10. windows批处理protoc生成C++代码

    1 首先需要生成protoc的可执行文件,具体可以参考  https://www.cnblogs.com/cnxkey/articles/10152646.html 2 将单个protoc文件生成.h ...