首先,我有用于连接 Redis 服务器的包装数据源类。
我有一个 ip 端口和 passwd 等的初始化文件;
redis.ini.php文件内容为:
<?php
$config['redis']['instance1'] = array(
'default' => array(
'host' => '127.0.0.1',
'port' => '6379',
'timeout' => 5,
'pconnect' => 1,
'password' => '',
)
);
$config['redis']['instance2'] = array(
'default' => array(
'host' => '127.0.0.1',
'port' => '6379',
'timeout' => 5,
'pconnect' => 1,
'password' => '',
)
);
类Datasource.php的代码是:
<?php
namespace common;
class Datasource {
public static $config_name;
public static $server_region;
public static $redis_config;
public function __construct() {}
public static function getRedis($config_name = NULL, $server_region = 'default') {
self::$config_name=$config_name;
self::$server_region=$server_region;
global $config;
self::$redis_config = $config['redis'][$config_name];
if (self::$config_name && self::$redis_config && self::$server_region) {
try {
self::$redis = new \Redis();
self::$redis->connect(self::$redis_config[$server_region]['host'], self::$redis_config[$server_region]['port']);
} catch (Exception $e) {
self::$redis = null;
}
} else {
self::$redis = null;
}
return self::$redis_config[$server_region]['host'] ;
}
}
现在,我想在 html 代码中使用这个类:
<body style="height:100%" >
<?php
include "o1ws1v/class/common/Datasource.php";
include 'o1ws1v/conf/redis.ini.php';
$redis_obj = common\Datasource::getRedis('instance1');
echo $redis_obj;
?>
</body>
但不幸的是,我无法在 html 中获取正确的值:127.0.0.1。
我发现问题出在 try{}catch{},当我删除这些代码时,它工作正常。
//delete these code, it works fine
try {
self::$redis = new \Redis();
self::$redis->connect(self::$redis_config[$server_region]['host'], self::$redis_config[$server_region]['port']);
} catch (Exception $e) {
self::$redis = null;
}
我一小时前在 stackoverflow 上问过一个问题,抱歉再问一个问题。我的老板今天要求我解决这个问题。
我已经定义了我的 redis 服务器,没有密码用于日志记录。连接redis服务器似乎没有问题,谁能帮帮我?
最佳答案
我已经解决了这个问题
self::$redis = new \Redis();// it is wrong
$redis=new \Redis();//it is right
关于php - 如何使用 init 文件连接到 redis 服务器,没有 passwd,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50808659/