文档地址
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如何使用自定义连接池完成。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。