关于hyperf:hyperf如何使用自定义连接池pool

文档地址

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如何应用自定义连接池实现。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理