PHP code example of easyswoole / pool

1. Go to this page and download the library: Download easyswoole/pool library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

easyswoole / pool example snippets



EasySwoole\Pool\AbstractPool;
use EasySwoole\Pool\Config;
use EasySwoole\Pool\ObjectInterface;

class DemoObject implements ObjectInterface
{
    private bool $open = true;
    public array $context = [];

    public function beforeUse(): bool
    {
        return $this->open;
    }

    public function intervalCheck(): bool
    {
        return $this->open;
    }

    public function objectRestore(): void
    {
        $this->context = [];
    }

    public function gc(): void
    {
        $this->open = false;
    }

    public function execute(): string
    {
        if (!$this->open) {
            throw new RuntimeException('对象已关闭');
        }
        return 'ok';
    }
}

class DemoPool extends AbstractPool
{
    protected function createObject(): ObjectInterface
    {
        // 实际连接在这里建立;失败时抛出异常。
        return new DemoObject();
    }
}

$config = new Config([
    'minObjectNum' => 2,
    'maxObjectNum' => 16,
    'getObjectTimeout' => 3.0,
    'intervalCheckTime' => 5000,
    'intervalCheckBatchSize' => 8,
]);
$pool = new DemoPool($config);

Swoole\Coroutine\run(function () use ($pool) {
    try {
        $pool->keepMin();
        $result = $pool->invoke(function (DemoObject $object) {
            $object->context['request'] = 'demo';
            return $object->execute();
        });
        echo $result . PHP_EOL;
    } catch (Throwable $error) {
        error_log($error->getMessage());
    } finally {
        // 独立脚本结束时停止定时器并清理空闲对象。
        // 常驻服务在停机时处理,不要每个请求都 destroy。
        $pool->destroy();
    }
});

$config = new Config([
    'minObjectNum' => 0,
    'maxObjectNum' => 4,
]);
$config->setIntervalCheckBatchSize(2)
    ->setIntervalCheckTime(1000)
    ->setGetObjectTimeout(0.5)
    ->setExtraConf(['endpoint' => 'service.example']);

$singleConfig = new Config(['minObjectNum' => 1, 'maxObjectNum' => 1]);
// 或先降低最小数量,再降低最大数量。
$singleConfig = (new Config())->setMinObjectNum(1)->setMaxObjectNum(1);

$object = $pool->getObj(0.5);
if ($object === null) {
    throw new RuntimeException('对象不可用');
}
try {
    $result = $object->execute();
} finally {
    $pool->recycleObj($object);
}

$object = $pool->getObj();
if ($object !== null) {
    // 业务已判定该连接失效。
    $pool->unsetObj($object);
}

$result = $pool->invoke(function (DemoObject $object) {
    return $object->execute();
}, 0.5);

$first = $pool->defer(0.5);
$second = $pool->defer();
assert($first === $second); // 同一池、同一协程复用同一个对象。
$first->execute();
// 此处没有自动归还;直到协程退出才归还。

$added = $pool->keepMin();  // 按 minObjectNum 补充。
$added = $pool->keepMin(10); // 补充到目标总数量,受 maxObjectNum 限制。

$state = $pool->status();
// ['createdNum' => 2, 'loadAverageTime' => 0.0]
$config = $pool->getConfig();

use EasySwoole\Pool\Manager;

$manager = Manager::getInstance();
$manager->register($pool, 'service');
$registered = $manager->get('service'); // 未注册返回 null。
if ($registered !== null) {
    $result = $registered->invoke(fn (DemoObject $object) => $object->execute());
}

// 前提:没有活动借用、建连或健康检查。
$pool->reset();
$result = $pool->invoke(fn (DemoObject $object) => $object->execute());
$pool->destroy();
bash
composer install
vendor/bin/phpunit --bootstrap vendor/autoload.php --do-not-cache-result tests/PoolRegressionTest.php