This commit is contained in:
as2252258@163.com
2021-08-08 02:42:55 +08:00
parent b471ea3f5e
commit 8c74ed4d00
6 changed files with 543 additions and 599 deletions
-11
View File
@@ -439,16 +439,6 @@ abstract class BaseApplication extends Component
} }
/**
* @return Pool
* @throws Exception
*/
public function getClientsPool(): Pool
{
return $this->get('clientsPool');
}
/** /**
* @param $array * @param $array
* @throws \ReflectionException * @throws \ReflectionException
@@ -493,7 +483,6 @@ abstract class BaseApplication extends Component
'error' => ['class' => ErrorHandler::class], 'error' => ['class' => ErrorHandler::class],
'connections' => ['class' => Connection::class], 'connections' => ['class' => Connection::class],
'redis_connections' => ['class' => SRedis::class], 'redis_connections' => ['class' => SRedis::class],
'clientsPool' => ['class' => Pool::class],
'config' => ['class' => Config::class], 'config' => ['class' => Config::class],
'logger' => ['class' => Logger::class], 'logger' => ['class' => Logger::class],
'annotation' => ['class' => SAnnotation::class], 'annotation' => ['class' => SAnnotation::class],
-1
View File
@@ -48,7 +48,6 @@ use Snowflake\Pool\Pool;
* @property HttpFilter $filter * @property HttpFilter $filter
* @property RPCProducer $rpc * @property RPCProducer $rpc
* @property Shutdown $shutdown * @property Shutdown $shutdown
* @property Pool $clientsPool
*/ */
trait TraitApplication trait TraitApplication
{ {
+24
View File
@@ -0,0 +1,24 @@
<?php
namespace Snowflake\Pool;
use JetBrains\PhpStorm\Pure;
trait Alias
{
/**
* @param $cds
* @param false $isMaster
* @return string
*/
#[Pure] public function name($cds, bool $isMaster = false): string
{
if ($isMaster === true) {
return $cds . '_master';
} else {
return $cds . '_slave';
}
}
}
+189 -214
View File
@@ -20,243 +20,218 @@ use Throwable;
class Connection extends Component class Connection extends Component
{ {
private ?Pool $clientsPool = null; use Alias;
/** /**
* @param $cds * @param $cds
* @return bool * @return bool
* *
* db is in transaction * db is in transaction
* @throws Exception * @throws Exception
*/ */
public function inTransaction($cds): bool public function inTransaction($cds): bool
{ {
$name = $this->getPool()->name('Mysql:' . $cds, true); $name = $this->name('Mysql:' . $cds, true);
return Context::getContext('begin_' . $name) == 0; return Context::getContext('begin_' . $name) == 0;
} }
/** /**
* @param $coroutineName * @param $coroutineName
* @throws Exception * @throws Exception
*/ */
public function beginTransaction($coroutineName) public function beginTransaction($coroutineName)
{ {
$coroutineName = $this->getPool()->name('Mysql:' . $coroutineName, true); $coroutineName = $this->name('Mysql:' . $coroutineName, true);
if (!Context::hasContext('begin_' . $coroutineName)) { if (!Context::hasContext('begin_' . $coroutineName)) {
Context::setContext('begin_' . $coroutineName, 0); Context::setContext('begin_' . $coroutineName, 0);
} }
Context::increment('begin_' . $coroutineName); if (Context::increment('begin_' . $coroutineName) != 0) {
if (Context::getContext('begin_' . $coroutineName) != 0) { return;
return; }
} $connection = Context::getContext($coroutineName);
$connection = Context::getContext($coroutineName); if (!$connection->inTransaction()) {
if ($connection instanceof PDO && !$connection->inTransaction()) { $connection->beginTransaction();
$connection->beginTransaction(); }
} }
}
/** /**
* @param $coroutineName * @param $coroutineName
* @throws Exception * @throws Exception
*/ */
public function commit($coroutineName) public function commit($coroutineName)
{ {
$coroutineName = $this->getPool()->name('Mysql:' . $coroutineName, true); $coroutineName = $this->name('Mysql:' . $coroutineName, true);
if (!Context::hasContext('begin_' . $coroutineName)) { if (Context::decrement('begin_' . $coroutineName) != 0) {
return; return;
} }
if (Context::decrement('begin_' . $coroutineName) > 0) { $connection = Context::getContext($coroutineName);
return; if ($connection->inTransaction()) {
} $connection->commit();
$connection = Context::getContext($coroutineName); }
if (!($connection instanceof PDO)) { }
return;
}
Context::setContext('begin_' . $coroutineName, 0);
if ($connection->inTransaction()) {
$connection->commit();
}
}
/** /**
* @param $coroutineName * @param $coroutineName
* @throws Exception * @throws Exception
*/ */
public function rollback($coroutineName) public function rollback($coroutineName)
{ {
$coroutineName = $this->getPool()->name('Mysql:' . $coroutineName, true); $coroutineName = $this->name('Mysql:' . $coroutineName, true);
if (!Context::hasContext('begin_' . $coroutineName)) { if (Context::decrement('begin_' . $coroutineName) != 0) {
return; return;
} }
if (Context::decrement('begin_' . $coroutineName) > 0) { if (($connection = Context::getContext($coroutineName)) instanceof PDO) {
return; if ($connection->inTransaction()) {
} $connection->rollBack();
if (($connection = Context::getContext($coroutineName)) instanceof PDO) { }
if ($connection->inTransaction()) { }
$connection->rollBack(); }
}
}
Context::setContext('begin_' . $coroutineName, 0);
}
/** /**
* @param mixed $config * @param mixed $config
* @param bool $isMaster * @param bool $isMaster
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public function get(mixed $config, bool $isMaster = false): mixed public function get(mixed $config, bool $isMaster = false): ?PDO
{ {
$coroutineName = $this->getPool()->name('Mysql:' . $config['cds'], $isMaster); $coroutineName = $this->name('Mysql:' . $config['cds'], $isMaster);
if (($pdo = Context::getContext($coroutineName)) instanceof PDO) { if (($pdo = Context::getContext($coroutineName)) instanceof PDO) {
return $pdo; return $pdo;
} }
if (Coroutine::getCid() === -1) { /** @var PDO $connections */
$connections = $this->createClient($coroutineName, $config); $connections = $this->getPool()->get($coroutineName, $this->create($coroutineName, $config));
} else { if ($number = Context::getContext('begin_' . $coroutineName)) {
/** @var PDO $connections */ $number > 0 && $connections->beginTransaction();
$connections = $this->getPool()->getFromChannel($coroutineName); }
if (empty($connections)) { return Context::setContext($coroutineName, $connections);
$connections = $this->createClient($coroutineName, $config); }
}
}
if ($number = Context::getContext('begin_' . $coroutineName)) {
$number > 0 && $connections->beginTransaction();
}
return Context::setContext($coroutineName, $connections);
}
/** /**
* @param $name * @param $coroutineName
* @param $isMaster * @param $config
* @param $max * @return \Closure
* @throws Exception */
*/ public function create($coroutineName, $config)
public function initConnections($name, $isMaster, $max) {
{ return static function () use ($coroutineName, $config) {
$this->getPool()->initConnections($name, $isMaster, $max); if (Coroutine::getCid() === -1) {
} Runtime::enableCoroutine(false);
}
$cds = 'mysql:dbname=' . $config['database'] . ';host=' . $config['cds'];
$link = new PDO($cds, $config['username'], $config['password'], [
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_CASE => PDO::CASE_NATURAL,
PDO::ATTR_TIMEOUT => 60,
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES ' . ($config['charset'] ?? 'utf8mb4')
]);
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$link->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, false);
$link->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_EMPTY_STRING);
return $link;
};
}
/** /**
* @param string $name * @param $name
* @param mixed $config * @param $isMaster
* @return PDO * @param $max
* @throws Exception * @throws Exception
*/ */
public function createClient(string $name, mixed $config): PDO public function initConnections($name, $isMaster, $max)
{ {
if (Coroutine::getCid() === -1) { $this->getPool()->initConnections($name, $isMaster, $max);
Runtime::enableCoroutine(false); }
}
$cds = 'mysql:dbname=' . $config['database'] . ';host=' . $config['cds'];
$link = new PDO($cds, $config['username'], $config['password'], [
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_CASE => PDO::CASE_NATURAL,
PDO::ATTR_TIMEOUT => 60,
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES ' . ($config['charset'] ?? 'utf8mb4')
]);
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$link->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, false);
$link->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_EMPTY_STRING);
return $link;
}
/** /**
* @param $coroutineName * @param $coroutineName
* @param $isMaster * @param $isMaster
* @throws Exception * @throws Exception
*/ */
public function release($coroutineName, $isMaster) public function release($coroutineName, $isMaster)
{ {
$coroutineName = $this->getPool()->name('Mysql:' . $coroutineName, $isMaster); $coroutineName = $this->name('Mysql:' . $coroutineName, $isMaster);
/** @var PDO $client */
/** @var PDO $client */ if (!($client = Context::getContext($coroutineName)) instanceof PDO) {
if (!($client = Context::getContext($coroutineName)) instanceof PDO) { return;
return; }
} if ($client->inTransaction()) {
if ($client->inTransaction()) { return;
return; }
} $this->getPool()->push($coroutineName, $client);
$this->getPool()->push($coroutineName, $client); Context::remove($coroutineName);
Context::remove($coroutineName); }
}
/** /**
* @param $coroutineName * @param $coroutineName
* @return bool * @return bool
*/ */
private function hasClient($coroutineName): bool private function hasClient($coroutineName): bool
{ {
return Context::hasContext($coroutineName); return Context::hasContext($coroutineName);
} }
/** /**
* batch release * batch release
* @throws Exception * @throws Exception
*/ */
public function connection_clear($name, $isMaster) public function connection_clear($name, $isMaster)
{ {
$this->getPool()->clean($this->getPool()->name($name, $isMaster)); $this->getPool()->clean($this->name($name, $isMaster));
} }
/** /**
* @param string $name * @param string $name
* @param mixed $client * @param mixed $client
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
public function checkCanUse(string $name, mixed $client): bool public function checkCanUse(string $name, mixed $client): bool
{ {
try { try {
if (empty($client) || !($client instanceof PDO)) { if (empty($client) || !($client instanceof PDO)) {
$result = false; $result = false;
} else { } else {
$result = true; $result = true;
} }
} catch (Error | Throwable $exception) { } catch (Error | Throwable $exception) {
$result = $this->addError($exception, 'mysql'); $result = $this->addError($exception, 'mysql');
} finally { } finally {
if (!$result) { return $result;
$this->getPool()->decrement($name); }
} }
return $result;
}
}
/** /**
* @param $coroutineName * @param $coroutineName
* @param bool $isMaster * @param bool $isMaster
* @throws Exception * @throws Exception
*/ */
public function disconnect($coroutineName, bool $isMaster = false) public function disconnect($coroutineName, bool $isMaster = false)
{ {
Context::remove($coroutineName); Context::remove($coroutineName);
$coroutineName = $this->getPool()->name('Mysql:' . $coroutineName, $isMaster); $coroutineName = $this->name('Mysql:' . $coroutineName, $isMaster);
$this->getPool()->clean($coroutineName); $this->getPool()->clean($coroutineName);
} }
/** /**
* @return Pool * @return Pool
* @throws Exception * @throws Exception
*/ */
public function getPool(): Pool public function getPool(): Pool
{ {
if (!$this->clientsPool) { return Snowflake::getDi()->get(Pool::class);
$this->clientsPool = Snowflake::app()->getClientsPool(); }
}
return $this->clientsPool;
}
} }
+238 -271
View File
@@ -22,311 +22,278 @@ use Swoole\Timer;
class Pool extends Component class Pool extends Component
{ {
/** @var Channel[] */ /** @var Channel[] */
private static array $_connections = []; private static array $_connections = [];
public int $max = 60; public int $max = 60;
public int $creates = -1; public int $creates = -1;
private array $_times = [];
use Alias;
private array $_times = []; /**
* @return array
protected static array $hasCreate = []; * @throws ConfigException
*/
private function getClearTime(): array
{
$firstClear = Config::get('pool.clear.start', 600);
$lastClear = Config::get('pool.clear.end', 300);
return [$firstClear, $lastClear];
}
/** /**
* @param string $name * @throws Exception
*/ */
public function increment(string $name) public function Heartbeat_detection($ticker)
{ {
if (!isset(static::$hasCreate[$name])) { if (env('state') == 'exit') {
static::$hasCreate[$name] = 0; Timer::clear($this->creates);
} foreach (static::$_connections as $channel) {
static::$hasCreate[$name] += 1; $this->flush($channel, 0);
} $channel->close();
}
static::$_connections = [];
$this->creates = -1;
} else {
$this->heartbeat_flush();
}
}
/** /**
* @param string $name * @throws ConfigException
*/ * @throws Exception
public function decrement(string $name) */
{ private function heartbeat_flush()
if (!isset(static::$hasCreate[$name])) { {
return; $num = [];
} $total = 0;
if (static::$hasCreate[$name] <= 0) { $min = Config::get('databases.pool.min', 1);
return; foreach (static::$_connections as $key => $channel) {
} if (!isset($num[$key])) {
static::$hasCreate[$name] -= 1; $num[$key] = 0;
} }
if (time() - ($this->_times[$key] ?? time()) > 120) {
$this->flush($channel, 0);
} else if ($channel->length() > $min) {
$this->flush($channel, $min);
}
$num[$key] += ($length = $channel->length());
$total += $length;
}
$this->clear($total, $num);
}
/** /**
* @return array * @param $total
* @throws ConfigException * @throws \Exception
*/ */
private function getClearTime(): array private function clear($total, $num)
{ {
$firstClear = Config::get('pool.clear.start', 600); write(var_export($num, true), 'connections');
$lastClear = Config::get('pool.clear.end', 300); if ($total >= 1) {
return [$firstClear, $lastClear]; return;
} }
Timer::clear($this->creates);
if (Snowflake::isWorker() || Snowflake::isTask()) {
$this->debug('Worker #' . env('worker') . ' clear time tick.');
}
$this->creates = -1;
}
/** /**
* @throws Exception * @param $channel
*/ * @param $retain_number
public function Heartbeat_detection($ticker) * @throws Exception
{ */
if (env('state') == 'exit') { public function flush($channel, $retain_number)
Timer::clear($this->creates); {
foreach (static::$_connections as $channel) { $this->pop($channel, $retain_number);
$this->flush($channel, 0); }
$channel->close();
}
static::$_connections = [];
$this->creates = -1;
} else {
$this->heartbeat_flush();
}
}
/** /**
* @throws ConfigException * @param Channel $channel
* @throws Exception * @param $retain_number
*/ * @throws Exception
private function heartbeat_flush() */
{ protected function pop(Channel $channel, $retain_number): void
$num = []; {
$total = 0; if (Coroutine::getCid() === -1) {
$min = Config::get('databases.pool.min', 1); return;
foreach (static::$_connections as $key => $channel) { }
if (!isset($num[$key])) { while ($channel->length() > $retain_number) {
$num[$key] = 0; $connection = $channel->pop();
} if ($connection) {
if (time() - ($this->_times[$key] ?? time()) > 120) { unset($connection);
$this->flush($channel, 0); }
} else if ($channel->length() > $min) { }
$this->flush($channel, $min); }
}
$num[$key] += ($length = $channel->length());
if (str_starts_with($key, 'Mysql') && (Snowflake::isWorker() || Snowflake::isTask()) && $length > 0) {
$this->debug('Worker #' . env('worker') . ' use client -> ' . $key . ':' . $length);
}
$total += $length;
}
write(var_export($num, true), 'connections');
if ($total < 1) {
Timer::clear($this->creates);
if (Snowflake::isWorker() || Snowflake::isTask()) {
$this->debug('Worker #' . env('worker') . ' clear time tick.');
}
$this->creates = -1;
}
}
/** /**
* @param $channel * @param $name
* @param $retain_number * @param false $isMaster
* @throws Exception * @param int $max
*/ */
public function flush($channel, $retain_number) public function initConnections($name, bool $isMaster = false, int $max = 60)
{ {
$this->pop($channel, $retain_number); $name = $this->name($name, $isMaster);
} if (isset(static::$_connections[$name]) && static::$_connections[$name] instanceof Channel) {
return;
}
if (Coroutine::getCid() === -1) {
return;
}
if ($this->creates === -1) {
$this->creates = Timer::tick(60000, [$this, 'Heartbeat_detection']);
}
static::$_connections[$name] = new Channel($max);
$this->max = $max;
}
/** /**
* @param Channel $channel * @param $name
* @param $retain_number * @return Channel
* @throws Exception * @throws ConfigException
*/ * @throws Exception
protected function pop(Channel $channel, $retain_number): void */
{ private function getChannel($name): Channel
if (Coroutine::getCid() === -1) { {
return; if (!isset(static::$_connections[$name])) {
} static::$_connections[$name] = new Channel(Config::get('databases.pool.max', 10));
while ($channel->length() > $retain_number) { }
$connection = $channel->pop(); if (static::$_connections[$name]->errCode == SWOOLE_CHANNEL_CLOSED) {
if ($connection) { throw new Exception('Channel is Close.');
unset($connection); }
} if ($this->creates === -1) {
} $this->creates = Timer::tick(60000, [$this, 'Heartbeat_detection']);
} }
return static::$_connections[$name];
}
/** /**
* @param $name * @param $name
* @param false $isMaster * @return array
* @param int $max * @throws Exception
*/ */
public function initConnections($name, bool $isMaster = false, int $max = 60) public function get($name, $callback): mixed
{ {
$name = $this->name($name, $isMaster); if (Coroutine::getCid() === -1) {
if (isset(static::$_connections[$name]) && static::$_connections[$name] instanceof Channel) { return $callback();
return; }
} $this->_times[$name] = time();
if (Coroutine::getCid() === -1) { $channel = $this->getChannel($name);
return; if (!$channel->isEmpty()) {
} $connection = $channel->pop();
if ($this->creates === -1) { if ($this->checkCanUse($name, $connection)) {
$this->creates = Timer::tick(60000, [$this, 'Heartbeat_detection']); return $connection;
} }
static::$_connections[$name] = new Channel($max); }
$this->max = $max; return $callback();
} }
/** /**
* @param $name * @param $name
* @return Channel * @return bool
* @throws ConfigException * @throws \Snowflake\Exception\ConfigException
* @throws Exception */
*/ public function isNull($name): bool
private function getChannel($name): Channel {
{ return $this->getChannel($name)->isEmpty();
if (!isset(static::$_connections[$name])) { }
static::$_connections[$name] = new Channel(Config::get('databases.pool.max', 10));
}
if (static::$_connections[$name]->errCode == SWOOLE_CHANNEL_CLOSED){
throw new Exception('Channel is Close.');
}
if ($this->creates === -1) {
$this->creates = Timer::tick(60000, [$this, 'Heartbeat_detection']);
}
return static::$_connections[$name];
}
/** /**
* @param $name * @param string $name
* @return array * @param mixed $client
* @throws Exception * @return bool
*/ * 检查连接可靠性
public function getFromChannel($name): mixed */
{ public function checkCanUse(string $name, mixed $client): bool
$this->_times[$name] = time(); {
$channel = $this->getChannel($name); return true;
if (!$channel->isEmpty()) { }
$connection = $channel->pop();
if ($this->checkCanUse($name, $connection)) {
return $connection;
}
}
return null;
}
/** /**
* @param $cds * @param string $name
* @param false $isMaster * @return bool
* @return string */
*/ public function hasItem(string $name): bool
#[Pure] public function name($cds, bool $isMaster = false): string {
{ if (isset(static::$_connections[$name])) {
if ($isMaster === true) { return !static::$_connections[$name]->isEmpty();
return $cds . '_master'; }
} else { return false;
return $cds . '_slave'; }
}
}
/** /**
* @param string $name * @param string $name
* @param mixed $client * @return mixed
* @return bool */
* 检查连接可靠性 public function size(string $name): mixed
*/ {
public function checkCanUse(string $name, mixed $client): bool if (Coroutine::getCid() === -1) {
{ return 0;
return true; }
} if (!isset(static::$_connections[$name])) {
return 0;
}
return static::$_connections[$name]->length();
}
/** /**
* @param array $config * @param string $name
* @param bool $isMaster * @param mixed $client
* @return mixed * @throws ConfigException
* @throws Exception */
*/ public function push(string $name, mixed $client)
public function get(mixed $config, bool $isMaster): mixed {
{ if (Coroutine::getCid() === -1) {
throw new Exception('Undefined system processing function.'); return;
} }
$channel = $this->getChannel($name);
if (!$channel->isFull()) {
$channel->push($client);
}
unset($client);
}
/** /**
* @param string $name * @param string $name
* @return bool * @throws Exception
*/ */
public function hasItem(string $name): bool public function clean(string $name)
{ {
if (isset(static::$_connections[$name])) { if (Coroutine::getCid() === -1 || !isset(static::$_connections[$name])) {
return !static::$_connections[$name]->isEmpty(); return;
} }
return false; $channel = static::$_connections[$name];
} $this->pop($channel, 0);
}
/** /**
* @param string $name * @return Channel[]
* @return mixed */
*/ protected function getChannels(): array
public function size(string $name): mixed {
{ return static::$_connections;
if (Coroutine::getCid() === -1) { }
return 0;
}
if (!isset(static::$_connections[$name])) {
return 0;
}
return static::$_connections[$name]->length();
}
/**
* @param string $name
* @param mixed $client
* @throws ConfigException
*/
public function push(string $name, mixed $client)
{
if (Coroutine::getCid() === -1) {
return;
}
$channel = $this->getChannel($name);
if (!$channel->isFull()) {
$channel->push($client);
}
unset($client);
}
/**
* @param string $name
* @throws Exception
*/
public function clean(string $name)
{
if (Coroutine::getCid() === -1 || !isset(static::$_connections[$name])) {
return;
}
$channel = static::$_connections[$name];
$this->pop($channel, 0);
}
/**
* @return Channel[]
*/
protected function getChannels(): array
{
return static::$_connections;
}
} }
+92 -102
View File
@@ -22,120 +22,110 @@ use Swoole\Runtime;
class Redis extends Component class Redis extends Component
{ {
private ?Pool $clientsPool = null; use Alias;
/** /**
* @param mixed $config * @param mixed $config
* @param bool $isMaster * @param bool $isMaster
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public function get(mixed $config, bool $isMaster = false): mixed public function get(mixed $config, bool $isMaster = false): mixed
{ {
$coroutineName = $this->getPool()->name('Redis:' . $config['host'], $isMaster); $coroutineName = $this->name('Redis:' . $config['host'], $isMaster);
if (Context::hasContext($coroutineName)) { if (Context::hasContext($coroutineName)) {
return Context::getContext($coroutineName); return Context::getContext($coroutineName);
} }
if (Coroutine::getCid() === -1) { $clients = $this->getPool()->get($coroutineName, $this->create($coroutineName, $config));
return Context::setContext($coroutineName, $this->createClient($coroutineName, $config)); return Context::setContext($coroutineName, $clients);
} }
$clients = $this->getPool()->getFromChannel($coroutineName);
if (empty($clients)) {
return Context::setContext($coroutineName, $this->createClient($coroutineName, $config));
}
return Context::setContext($coroutineName, $clients);
}
/** /**
* @param string $name * @param string $name
* @param mixed $config * @param mixed $config
* @return SRedis * @return SRedis
* @throws RedisConnectException * @throws RedisConnectException
* @throws Exception * @throws Exception
*/ */
public function createClient(string $name, mixed $config): SRedis public function create(string $name, mixed $config): \Closure
{ {
if (Coroutine::getCid() === -1) { return static function () use ($name, $config) {
Runtime::enableCoroutine(false); if (Coroutine::getCid() === -1) {
} Runtime::enableCoroutine(false);
$redis = new SRedis(); }
if (!$redis->pconnect($config['host'], (int)$config['port'], $config['timeout'])) { $redis = new SRedis();
throw new RedisConnectException(sprintf('The Redis Connect %s::%d Fail.', $config['host'], $config['port'])); if (!$redis->pconnect($config['host'], (int)$config['port'], $config['timeout'])) {
} throw new RedisConnectException(sprintf('The Redis Connect %s::%d Fail.', $config['host'], $config['port']));
if (!empty($config['auth']) && !$redis->auth($config['auth'])) { }
throw new RedisConnectException(sprintf('Redis Error: %s, Host %s, Auth %s', $redis->getLastError(), $config['host'], $config['auth'])); if (!empty($config['auth']) && !$redis->auth($config['auth'])) {
} throw new RedisConnectException(sprintf('Redis Error: %s, Host %s, Auth %s', $redis->getLastError(), $config['host'], $config['auth']));
if (!isset($config['read_timeout'])) { }
$config['read_timeout'] = 10; if (!isset($config['read_timeout'])) {
} $config['read_timeout'] = 10;
$redis->select($config['databases']); }
$redis->setOption(SRedis::OPT_READ_TIMEOUT, $config['read_timeout']); $redis->select($config['databases']);
$redis->setOption(SRedis::OPT_PREFIX, $config['prefix']); $redis->setOption(SRedis::OPT_READ_TIMEOUT, $config['read_timeout']);
$redis->setOption(SRedis::OPT_PREFIX, $config['prefix']);
$this->getPool()->increment($name); return $redis;
};
return $redis; }
}
/** /**
* @param array $config * @param array $config
* @param bool $isMaster * @param bool $isMaster
* @throws ConfigException * @throws ConfigException
* @throws Exception * @throws Exception
*/ */
public function release(array $config, bool $isMaster = false) public function release(array $config, bool $isMaster = false)
{ {
$coroutineName = $this->getPool()->name('Redis:' . $config['host'], $isMaster); $coroutineName = $this->name('Redis:' . $config['host'], $isMaster);
if (!Context::hasContext($coroutineName)) { if (!Context::hasContext($coroutineName)) {
return; return;
} }
$this->getPool()->push($coroutineName, Context::getContext($coroutineName)); $this->getPool()->push($coroutineName, Context::getContext($coroutineName));
Context::remove($coroutineName); Context::remove($coroutineName);
} }
/** /**
* @param array $config * @param array $config
* @param bool $isMaster * @param bool $isMaster
* @throws Exception * @throws Exception
*/ */
public function destroy(array $config, bool $isMaster = false) public function destroy(array $config, bool $isMaster = false)
{ {
$coroutineName = $this->getPool()->name('Redis:' . $config['host'], $isMaster); $coroutineName = $this->name('Redis:' . $config['host'], $isMaster);
if (Context::hasContext($coroutineName)) { if (Context::hasContext($coroutineName)) {
$this->getPool()->decrement($coroutineName); $this->getPool()->decrement($coroutineName);
} }
$this->getPool()->clean($coroutineName); $this->getPool()->clean($coroutineName);
Context::remove($coroutineName); Context::remove($coroutineName);
} }
/** /**
* @return Pool * @return Pool
* @throws Exception * @throws Exception
*/ */
public function getPool(): Pool public function getPool(): Pool
{ {
if (!$this->clientsPool) { return Snowflake::getDi()->get(Pool::class);
$this->clientsPool = Snowflake::app()->getClientsPool(); }
}
return $this->clientsPool;
}
/** /**
* @param $name * @param $name
* @param $isMaster * @param $isMaster
* @param $max * @param $max
* @throws Exception * @throws Exception
*/ */
public function initConnections($name, $isMaster, $max) public function initConnections($name, $isMaster, $max)
{ {
$this->getPool()->initConnections($name, $isMaster, $max); $this->getPool()->initConnections($name, $isMaster, $max);
} }
} }