× 警告!旧版文档已经暂停维护,请查看新版文档。点击前往新版文档

Library

Swoole在v4版本后内置了Library模块,使用PHP代码编写内核功能,使得底层设施更加稳定可靠

该模块可通过composer单独安装,使用时需通过ini配置swoole.enable_library=Off关闭扩展内置的library

相关PHP源码:点此查看

目前提供了以下工具组件:

Coroutine

ConnectionPool

原始连接池,基于Channel自动调度,支持传入任意构造器(callable),构造器需返回一个连接对象

  • get方法获取连接(连接池未满时会创建新的连接)
  • put方法回收连接
  • fill方法填充连接池(提前创建连接)
  • close关闭连接池

Database

各种数据库连接池和对象代理的高级封装,支持自动断线重连 目前包含PDO,Mysqli,Redis三种类型的数据库支持:

  • PDOConfig, PDOProxy, PDOPool
  • MysqliConfig, MysqliProxy, MysqliPool
  • RedisConfig, RedisProxy, RedisPool

注意:MySQL断线重连可自动恢复大部分连接上下文(fetch模式,已设置的attribute,已编译的Statement等等),但诸如事务等上下文无法恢复,若处于事务中的连接断开,将会抛出异常,请自行评估重连的可靠性

注意:将处于事务中的连接归还给连接池是未定义行为,开发者需要自己保证归还的连接是可重用的

注意:若有连接对象出现异常不可重用,开发者需要调用$pool->put(null);归还一个空连接以保证连接池的数量平衡

PDOPool例子

<?php
declare(strict_types=1);

use Swoole\Coroutine;
use Swoole\Database\PDOConfig;
use Swoole\Database\PDOPool;
use Swoole\Runtime;

const N = 1024;
Runtime::enableCoroutine();
$s = microtime(true);
Coroutine\run(function () {
    $pool = new PDOPool((new PDOConfig)
        ->withHost('127.0.0.1')
        ->withPort(3306)
        // ->withUnixSocket('/tmp/mysql.sock')
        ->withDbName('test')
        ->withCharset('utf8mb4')
        ->withUsername('root')
        ->withPassword('root')
    );
    for ($n = N; $n--;) {
        Coroutine::create(function () use ($pool) {
            $pdo = $pool->get();
            $statement = $pdo->prepare('SELECT ? + ?');
            if (!$statement) {
                throw new RuntimeException('Prepare failed');
            }
            $a = mt_rand(1, 100);
            $b = mt_rand(1, 100);
            $result = $statement->execute([$a, $b]);
            if (!$result) {
                throw new RuntimeException('Execute failed');
            }
            $result = $statement->fetchAll();
            if ($a + $b !== (int)$result[0][0]) {
                throw new RuntimeException('Bad result');
            }
            $pool->put($pdo);
        });
    }
});
$s = microtime(true) - $s;
echo 'Use ' . $s . 's for ' . N . ' queries' . PHP_EOL;

其它

此外还有Coroutine\ServerCURL hook 等核心功能都是由PHP代码实现的

例子仓库

Examples