PHPackages                             yii-diandi/connection-pool - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. yii-diandi/connection-pool

ActiveLibrary[Database &amp; ORM](/categories/database)

yii-diandi/connection-pool
==========================

swoole连接池扩展类库

1.0.2(3y ago)03MITPHPPHP &gt;=7.0.0

Since Nov 29Pushed 3y ago1 watchersCompare

[ Source](https://github.com/yii-diandi/connection-pool)[ Packagist](https://packagist.org/packages/yii-diandi/connection-pool)[ Docs](https://github.com/yii-diandi/connection-pool)[ RSS](/packages/yii-diandi-connection-pool/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (1)Versions (4)Used By (0)

Connection pool
===============

[](#connection-pool)

A common connection pool based on Swoole is usually used as the database connection pool.

[![Latest Version](https://camo.githubusercontent.com/efb987adc63e68520254a5986bba50f541d3062d1ba09a003327810d36a6be45/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f72656c656173652f6f70656e2d736d662f636f6e6e656374696f6e2d706f6f6c2e737667)](https://github.com/open-smf/connection-pool/releases)[![PHP Version](https://camo.githubusercontent.com/412df6708db66e8a8d8c57db9d9ec5434817f780056c00d8524f0750fe72bfeb/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f6f70656e2d736d662f636f6e6e656374696f6e2d706f6f6c2e7376673f636f6c6f723d677265656e)](https://secure.php.net)[![Total Downloads](https://camo.githubusercontent.com/de26c1099f63827aa1a2968c5dc352264951be738283e04d489f8f70879891b2/68747470733a2f2f706f7365722e707567782e6f72672f6f70656e2d736d662f636f6e6e656374696f6e2d706f6f6c2f646f776e6c6f616473)](https://packagist.org/packages/open-smf/connection-pool)[![License](https://camo.githubusercontent.com/3da42794bc7fee596d9974fab862b124b342ec2da834719a0dbde5c6b0616707/68747470733a2f2f706f7365722e707567782e6f72672f6f70656e2d736d662f636f6e6e656374696f6e2d706f6f6c2f6c6963656e7365)](LICENSE)

Requirements
------------

[](#requirements)

DependencyRequirement[PHP](https://secure.php.net/manual/en/install.php)`>=7.0.0`[Swoole](https://github.com/swoole/swoole-src)`>=4.2.9` `Recommend 4.2.13+`Install
-------

[](#install)

> Install package via [Composer](https://getcomposer.org/).

```
composer require "open-smf/connection-pool:~1.0"
```

Usage
-----

[](#usage)

> See more [examples](examples).

- Available connectors

ConnectorConnection descriptionCoroutineMySQLConnectorInstance of `Swoole\Coroutine\MySQL`CoroutinePostgreSQLConnectorInstance of `Swoole\Coroutine\PostgreSQL`, require configuring `Swoole` with `--enable-coroutine-postgresql`CoroutineRedisConnectorInstance of `Swoole\Coroutine\Redis`PhpRedisConnectorInstance of `Redis`, require [redis](https://pecl.php.net/package/redis)PDOConnectorInstance of `PDO`, require [PDO](https://www.php.net/manual/en/book.pdo.php)YourConnector`YourConnector` must implement interface `ConnectorInterface`, any object can be used as a connection instance- Basic usage

```
use Smf\ConnectionPool\ConnectionPool;
use Smf\ConnectionPool\Connectors\CoroutineMySQLConnector;
use Swoole\Coroutine\MySQL;

go(function () {
    // All MySQL connections: [10, 30]
    $pool = new ConnectionPool(
        [
            'minActive'         => 10,
            'maxActive'         => 30,
            'maxWaitTime'       => 5,
            'maxIdleTime'       => 20,
            'idleCheckInterval' => 10,
        ],
        new CoroutineMySQLConnector,
        [
            'host'        => '127.0.0.1',
            'port'        => '3306',
            'user'        => 'root',
            'password'    => 'xy123456',
            'database'    => 'mysql',
            'timeout'     => 10,
            'charset'     => 'utf8mb4',
            'strict_type' => true,
            'fetch_mode'  => true,
        ]
    );
    echo "Initializing connection pool\n";
    $pool->init();
    defer(function () use ($pool) {
        echo "Closing connection pool\n";
        $pool->close();
    });

    echo "Borrowing the connection from pool\n";
    /**@var MySQL $connection */
    $connection = $pool->borrow();

    $status = $connection->query('SHOW STATUS LIKE "Threads_connected"');

    echo "Return the connection to pool as soon as possible\n";
    $pool->return($connection);

    var_dump($status);
});
```

- Usage in Swoole Server

```
use Smf\ConnectionPool\ConnectionPool;
use Smf\ConnectionPool\ConnectionPoolTrait;
use Smf\ConnectionPool\Connectors\CoroutineMySQLConnector;
use Smf\ConnectionPool\Connectors\PhpRedisConnector;
use Swoole\Coroutine\MySQL;
use Swoole\Http\Request;
use Swoole\Http\Response;
use Swoole\Http\Server;

class HttpServer
{
    use ConnectionPoolTrait;

    protected $swoole;

    public function __construct(string $host, int $port)
    {
        $this->swoole = new Server($host, $port);

        $this->setDefault();
        $this->bindWorkerEvents();
        $this->bindHttpEvent();
    }

    protected function setDefault()
    {
        $this->swoole->set([
            'daemonize'             => false,
            'dispatch_mode'         => 1,
            'max_request'           => 8000,
            'open_tcp_nodelay'      => true,
            'reload_async'          => true,
            'max_wait_time'         => 60,
            'enable_reuse_port'     => true,
            'enable_coroutine'      => true,
            'http_compression'      => false,
            'enable_static_handler' => false,
            'buffer_output_size'    => 4 * 1024 * 1024,
            'worker_num'            => 4, // Each worker holds a connection pool
        ]);
    }

    protected function bindHttpEvent()
    {
        $this->swoole->on('Request', function (Request $request, Response $response) {
            $pool1 = $this->getConnectionPool('mysql');
            /**@var MySQL $mysql */
            $mysql = $pool1->borrow();
            $status = $mysql->query('SHOW STATUS LIKE "Threads_connected"');
            // Return the connection to pool as soon as possible
            $pool1->return($mysql);

            $pool2 = $this->getConnectionPool('redis');
            /**@var \Redis $redis */
            $redis = $pool2->borrow();
            $clients = $redis->info('Clients');
            // Return the connection to pool as soon as possible
            $pool2->return($redis);

            $json = [
                'status'  => $status,
                'clients' => $clients,
            ];
            // Other logic
            // ...
            $response->header('Content-Type', 'application/json');
            $response->end(json_encode($json));
        });
    }

    protected function bindWorkerEvents()
    {
        $createPools = function () {
            // All MySQL connections: [4 workers * 2 = 8, 4 workers * 10 = 40]
            $pool1 = new ConnectionPool(
                [
                    'minActive' => 2,
                    'maxActive' => 10,
                ],
                new CoroutineMySQLConnector,
                [
                    'host'        => '127.0.0.1',
                    'port'        => '3306',
                    'user'        => 'root',
                    'password'    => 'xy123456',
                    'database'    => 'mysql',
                    'timeout'     => 10,
                    'charset'     => 'utf8mb4',
                    'strict_type' => true,
                    'fetch_mode'  => true,
                ]);
            $pool1->init();
            $this->addConnectionPool('mysql', $pool1);

            // All Redis connections: [4 workers * 5 = 20, 4 workers * 20 = 80]
            $pool2 = new ConnectionPool(
                [
                    'minActive' => 5,
                    'maxActive' => 20,
                ],
                new PhpRedisConnector,
                [
                    'host'     => '127.0.0.1',
                    'port'     => '6379',
                    'database' => 0,
                    'password' => null,
                ]);
            $pool2->init();
            $this->addConnectionPool('redis', $pool2);
        };
        $closePools = function () {
            $this->closeConnectionPools();
        };
        $this->swoole->on('WorkerStart', $createPools);
        $this->swoole->on('WorkerStop', $closePools);
        $this->swoole->on('WorkerError', $closePools);
    }

    public function start()
    {
        $this->swoole->start();
    }
}

// Enable coroutine for PhpRedis
Swoole\Runtime::enableCoroutine();
$server = new HttpServer('0.0.0.0', 5200);
$server->start();
```

License
-------

[](#license)

[MIT](LICENSE)

###  Health Score

20

—

LowBetter than 14% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity3

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity43

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

3

Last Release

1260d ago

PHP version history (2 changes)1.0.0PHP &gt;=7.4.0

1.0.1PHP &gt;=7.0.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/46cef84bc40d75ea2a86c1746f139764841f3d133d34d951bf78ea39faffaa20?d=identicon)[wangchunsheng](/maintainers/wangchunsheng)

---

Top Contributors

[![yii-diandi](https://avatars.githubusercontent.com/u/34767187?v=4)](https://github.com/yii-diandi "yii-diandi (3 commits)")

---

Tags

swooleconnection-pooldatabase-connection-pool

### Embed Badge

![Health badge](/badges/yii-diandi-connection-pool/health.svg)

```
[![Health](https://phpackages.com/badges/yii-diandi-connection-pool/health.svg)](https://phpackages.com/packages/yii-diandi-connection-pool)
```

###  Alternatives

[open-smf/connection-pool

A common connection pool based on Swoole is usually used as the database connection pool.

223153.7k20](/packages/open-smf-connection-pool)[swoft/db

swoft database component

24167.4k11](/packages/swoft-db)[swlib/swpdo

Swoole Coroutine SQL component like PDO

6112.6k1](/packages/swlib-swpdo)[hyperf/database-pgsql

A pgsql handler for hyperf/database.

12282.0k13](/packages/hyperf-database-pgsql)[mix/database

Simple database for use in multiple execution environments, with support for FPM, Swoole, Workerman, and optional pools

1515.3k9](/packages/mix-database)[simple-swoole/db

A db component for Simps.

216.3k3](/packages/simple-swoole-db)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
