文档地址
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如何应用自定义连接池实现。
发表回复