* [refac] connect redis in baseHelper so that api can use it.

This commit is contained in:
liugang
2024-12-11 13:35:42 +08:00
committed by 朱金勇
parent e2b560d5db
commit f1f94474ff
2 changed files with 41 additions and 41 deletions
+41
View File
@@ -1093,6 +1093,47 @@ class baseHelper
{
throw EndResponseException::create($content);
}
/**
* 连接 Redis 服务器。
* Connect to Redis server.
*
* @param object $setting
* @static
* @access public
* @return object
*/
public static function connectRedis(object $setting)
{
if(!class_exists('Redis')) throw new Exception('The Redis extension is not installed.');
try
{
$redis = new Redis();
$version = phpversion('redis');
if(version_compare($version, '5.3.0', 'ge'))
{
$redis->connect($setting->host, (int)$setting->port, 1, null, 0, 0, ['auth' => [$setting->username ?: null, $setting->password ?: null]]);
}
else
{
$redis->connect($setting->host, (int)$setting->port, 1, null, 0, 0);
$redis->auth($setting->password ?: null);
}
if(!$redis->ping()) throw new Exception('Can not connect to Redis server.');
$databases = $redis->config('GET', 'databases');
if($setting->database >= $databases['databases']) throw new Exception("The database number is out of range. Your Redis server's max database number is " . ($databases['databases'] - 1) . '.');
return $redis;
}
catch(RedisException $e)
{
throw new Exception('Can not connect to Redis server. The error message is: ' . $e->getMessage());
}
}
}
//------------------------------- 常用函数。Some tool functions.-------------------------------//
-41
View File
@@ -433,47 +433,6 @@ class helper extends baseHelper
$checkFunc = 'check' . $operator;
return validater::$checkFunc($value1, $value2);
}
/**
* 连接 Redis 服务器。
* Connect to Redis server.
*
* @param object $setting
* @static
* @access public
* @return object
*/
public static function connectRedis(object $setting)
{
if(!class_exists('Redis')) throw new Exception('The Redis extension is not installed.');
try
{
$redis = new Redis();
$version = phpversion('redis');
if(version_compare($version, '5.3.0', 'ge'))
{
$redis->connect($setting->host, (int)$setting->port, 1, null, 0, 0, ['auth' => [$setting->username ?: null, $setting->password ?: null]]);
}
else
{
$redis->connect($setting->host, (int)$setting->port, 1, null, 0, 0);
$redis->auth($setting->password ?: null);
}
if(!$redis->ping()) throw new Exception('Can not connect to Redis server.');
$databases = $redis->config('GET', 'databases');
if($setting->database >= $databases['databases']) throw new Exception("The database number is out of range. Your Redis server's max database number is " . ($databases['databases'] - 1) . '.');
return $redis;
}
catch(RedisException $e)
{
throw new Exception('Can not connect to Redis server. The error message is: ' . $e->getMessage());
}
}
}
/**