This commit is contained in:
xl
2023-05-26 10:30:23 +08:00
parent fff3211e61
commit 13cc75765b
+172 -149
View File
@@ -10,6 +10,7 @@ declare(strict_types=1);
namespace Kiri\Redis; namespace Kiri\Redis;
use Exception; use Exception;
use JetBrains\PhpStorm\ArrayShape;
use Kiri; use Kiri;
use Kiri\Abstracts\Component; use Kiri\Abstracts\Component;
use Kiri\Events\EventProvider; use Kiri\Events\EventProvider;
@@ -32,107 +33,85 @@ use ReflectionException;
class Redis extends Component class Redis extends Component
{ {
public string $host = ''; public string $host = '';
public int $port = 6379; public int $port = 6379;
public string $prefix = 'api:'; public string $prefix = 'api:';
public string $auth = ''; public string $auth = '';
public int $databases = 0; public int $databases = 0;
public int $timeout = 30; public int $timeout = 30;
/** /**
* @var int * @var int
*/ */
public int $read_timeout = -1; public int $read_timeout = -1;
/** /**
* @var array|int[] * @var array|int[]
*/ */
public array $pool = ['min' => 1, 'max' => 100]; public array $pool = ['min' => 1, 'max' => 100];
/** /**
* @return void * @return void
* @throws Exception * @throws Exception
*/ */
public function init(): void public function init(): void
{ {
$config = $this->get_config(); on(OnWorkerExit::class, [$this, 'destroy']);
}
$length = \config('cache.redis.pool.max', 10);
on(OnWorkerExit::class, [$this, 'destroy']);
Kiri::getPool()->created($config['host'], $length, static function () use ($config) {
$redis = new \Redis();
if (!$redis->connect($config['host'], $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 ($config['read_timeout'] < 0) {
$config['read_timeout'] = 0;
}
$redis->select($config['databases']);
if ($config['read_timeout'] > 0) {
$redis->setOption(\Redis::OPT_READ_TIMEOUT, $config['read_timeout']);
}
$redis->setOption(\Redis::OPT_PREFIX, $config['prefix']);
return $redis;
});
}
/** /**
* @param $name * @param $name
* @param $arguments * @param $arguments
* @return mixed * @return mixed
* @throws * @throws
*/ */
public function __call($name, $arguments): mixed public function __call($name, $arguments): mixed
{ {
if (method_exists($this, $name)) { if (method_exists($this, $name)) {
$data = $this->{$name}(...$arguments); $data = $this->{$name}(...$arguments);
} else { } else {
$data = $this->proxy($name, $arguments); $data = $this->proxy($name, $arguments);
} }
return $data; return $data;
} }
/** /**
* @param $key * @param $key
* @param int $timeout * @param int $timeout
* @return bool * @return bool
* @throws RedisException */
*/ public function waite($key, int $timeout = 5): bool
public function waite($key, int $timeout = 5): bool {
{ $time = time();
$time = time(); while (!$this->setNx($key, '1')) {
while (!$this->setNx($key, '1')) { if (time() - $time >= $timeout) {
if (time() - $time >= $timeout) { return FALSE;
return FALSE; }
} usleep(1000);
usleep(1000); }
} $this->expire($key, $timeout);
$this->expire($key, $timeout); return TRUE;
return TRUE; }
}
/** /**
* @param $key * @param $key
* @param int $timeout * @param int $timeout
* @return bool|int * @return bool|int
* @throws Exception * @throws Exception
*/ */
public function lock($key, int $timeout = 5): bool|int public function lock($key, int $timeout = 5): bool|int
{ {
$script = <<<SCRIPT $script = <<<SCRIPT
local _nx = redis.call('setnx',KEYS[1], ARGV[1]) local _nx = redis.call('setnx',KEYS[1], ARGV[1])
if (_nx ~= 0) then if (_nx ~= 0) then
redis.call('expire',KEYS[1], ARGV[1]) redis.call('expire',KEYS[1], ARGV[1])
@@ -140,80 +119,124 @@ if (_nx ~= 0) then
end end
return 0 return 0
SCRIPT; SCRIPT;
return $this->eval($script, ['{lock}:' . $key, $timeout], 1); return $this->eval($script, ['{lock}:' . $key, $timeout], 1);
} }
/** /**
* @param $key * @param $key
* @return int * @return int
* @throws Exception * @throws Exception
*/ */
public function unlock($key): int public function unlock($key): int
{ {
return $this->del('{lock}:' . $key); return $this->del('{lock}:' . $key);
} }
/** /**
* @return void * @return void
* @throws * @throws
*/ */
public function destroy(): void public function destroy(): void
{ {
Kiri::getPool()->clean($this->host); $this->pool()->clean($this->host);
} }
/** /**
* @param $name * @param $name
* @param $arguments * @param $arguments
* @return mixed * @return mixed
* @throws ConfigException * @throws ConfigException
* @throws ContainerExceptionInterface * @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface * @throws NotFoundExceptionInterface
* @throws ReflectionException * @throws ReflectionException
*/ */
public function proxy($name, $arguments): mixed public function proxy($name, $arguments): mixed
{ {
$client = $this->getClient(); $client = $this->getClient();
try { try {
$response = $client->{$name}(...$arguments); $response = $client->{$name}(...$arguments);
} catch (\Throwable $throwable) { } catch (\Throwable $throwable) {
$response = addError($throwable, 'redis'); $response = addError($throwable, 'redis');
} finally { } finally {
Kiri::getPool()->push($this->host, $client); $this->pool()->push($this->host, $client);
} }
return $response; return $response;
} }
/** /**
* @return \Redis * @return \Redis
* @throws ConfigException * @throws ConfigException
* @throws ReflectionException * @throws ReflectionException
*/ */
private function getClient(): \Redis private function getClient(): \Redis
{ {
return Kiri::getPool()->get($this->host); return $this->pool()->get($this->host);
} }
/** /**
* @return array * @return Pool
*/ * @throws ReflectionException
public function get_config(): array */
{ protected function pool(): Pool
return [ {
'host' => $this->host, $pool = Kiri::getPool();
'port' => $this->port, if (!$pool->hasChannel($this->host)) {
'prefix' => $this->prefix, $config = $this->get_config();
'auth' => $this->auth, $length = \config('cache.redis.pool.max', 10);
'databases' => $this->databases, $pool->created($config['host'], $length, $this->connect($config));
'timeout' => $this->timeout, }
'read_timeout' => $this->read_timeout, return $pool;
'pool' => $this->pool }
];
}
/**
* @param $config
* @return \Closure
*/
protected function connect($config): \Closure
{
return static function () use ($config) {
$redis = new \Redis();
if (!$redis->connect($config['host'], $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 ($config['read_timeout'] < 0) {
$config['read_timeout'] = 0;
}
$redis->select($config['databases']);
if ($config['read_timeout'] > 0) {
$redis->setOption(\Redis::OPT_READ_TIMEOUT, $config['read_timeout']);
}
$redis->setOption(\Redis::OPT_PREFIX, $config['prefix']);
return $redis;
};
}
/**
* @return array
*/
#[ArrayShape(['host' => "string", 'port' => "int", 'prefix' => "string", 'auth' => "string", 'databases' => "int", 'timeout' => "int", 'read_timeout' => "int", 'pool' => "array|int[]"])]
public function get_config(): array
{
return [
'host' => $this->host,
'port' => $this->port,
'prefix' => $this->prefix,
'auth' => $this->auth,
'databases' => $this->databases,
'timeout' => $this->timeout,
'read_timeout' => $this->read_timeout,
'pool' => $this->pool
];
}
} }