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();
}
});