文档地址
https://hyperf.wiki/2.2/#/zh-…
如何定义连接池?
依照文档的要求在 app/Pool 门路下 PHP 文件 MyConnectionPool.php。此时文件内容
<?php
namespace App\Pool;
use Hyperf\Contract\ConnectionInterface;
use Hyperf\Pool\Pool;
use Pheanstalk\Pheanstalk;
class MyConnectionPool extends Pool
{public function createConnection(): ConnectionInterface
{return new MyConnection();
}
}
在办法 createConnetion 返回的是一个接口 ConnectionInterface,所以须要咱们自定义 MyConnection 类并实现接口 ConnectionInterface
<?php
namespace App\Pool;
use Hyperf\Contract\ConnectionInterface;
use Hyperf\Pool\Pool;
use Pheanstalk\Pheanstalk;
class MyConnectionPool extends Pool
{public function createConnection(): ConnectionInterface
{return new MyConnection();
}
}
class MyConnection implements ConnectionInterface
{public function getConnection(): Pheanstalk
{// TODO: Implement getConnection() method.
return Pheanstalk::create(env('BEANSTALK_HOST'), env('BEANSTALK__PORT'));
}
public function reconnect(): bool
{
return true;
// TODO: Implement reconnect() method.}
public function check(): bool
{
return true;
// TODO: Implement check() method.}
public function close(): bool
{
return true;
// TODO: Implement close() method.}
public function release(): void
{// TODO: Implement release() method.
}
}
在下面代码的示例中实现了对 beanstalkd 的连贯的创立。
如何应用?
在 app/Controller/IndexController.php 减少办法 get
public function get()
{$container = \Hyperf\Utils\ApplicationContext::getContainer();
$myConnectionPool = new MyConnectionPool($container);
$conn = $myConnectionPool->get();
$this->beans = $conn->getConnection();
$job = $this->beans->useTube("normal")->put('jj');
$conn->release();
return [$job->getData(), $job->getId()];
}
config/routes.php 减少路由,能拜访即可
Router::get('/get', [\App\Controller\IndexController::class, 'get']);
至此 hyperf 如何应用自定义连接池实现。