improve connection pools

This commit is contained in:
Torsten Dittmann 2021-06-22 11:16:29 +02:00
parent 05b7b3da24
commit 241255dabf
3 changed files with 14 additions and 15 deletions

View file

@ -1,10 +1,12 @@
<?php
namespace Appwrite\Database;
use Swoole\Coroutine\Channel;
abstract class Pool
{
protected Channel $pool;
protected $available = true;
protected $pool;
protected $size = 5;
abstract public function get();

View file

@ -4,14 +4,13 @@ namespace Appwrite\Database\Pool;
use Appwrite\Database\Pool;
use Appwrite\Extend\PDO;
use SplQueue;
use Swoole\Coroutine\Channel;
class PDOPool extends Pool
{
public function __construct(int $size, string $host = 'localhost', string $schema = 'appwrite', string $user = '', string $pass = '', string $charset = 'utf8mb4')
{
$this->pool = new SplQueue;
$this->size = $size;
$this->pool = new Channel($this->size = $size);
for ($i = 0; $i < $this->size; $i++) {
$pdo = new PDO(
"mysql:" .
@ -29,19 +28,19 @@ class PDOPool extends Pool
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true
]
);
$this->pool->enqueue($pdo);
$this->pool->push($pdo);
}
}
public function put(PDO $pdo)
{
$this->pool->enqueue($pdo);
$this->pool->push($pdo);
}
public function get(): PDO
{
if ($this->available && count($this->pool) > 0) {
return $this->pool->dequeue();
if ($this->available && !$this->pool->isEmpty()) {
return $this->pool->pop();
}
sleep(0.01);
return $this->get();

View file

@ -3,16 +3,14 @@
namespace Appwrite\Database\Pool;
use Appwrite\Database\Pool;
use SplQueue;
use Redis;
use Swoole\Coroutine\Channel;
class RedisPool extends Pool
{
public function __construct(int $size, string $host, int $port, array $auth = [])
{
$this->pool = new SplQueue;
$this->size = $size;
$this->pool = new Channel($this->size = $size);
for ($i = 0; $i < $this->size; $i++) {
$redis = new Redis();
$redis->pconnect($host, $port);
@ -22,19 +20,19 @@ class RedisPool extends Pool
$redis->auth($auth);
}
$this->pool->enqueue($redis);
$this->pool->push($redis);
}
}
public function put(Redis $redis)
{
$this->pool->enqueue($redis);
$this->pool->push($redis);
}
public function get(): Redis
{
if ($this->available && !$this->pool->isEmpty()) {
return $this->pool->dequeue();
return $this->pool->pop();
}
sleep(0.1);
return $this->get();