我正在使用phpredis将redis作为缓存存储。它运行得非常完美,我想提供一些故障转移的方式,以确保缓存功能始终可用(例如使用基于文件的缓存),即使redis服务器宕机。最初,我想到了以下代码:
<?php
$redis=new Redis();
try {
$redis->connect('127.0.0.1', 6379);
} catch (Exception $e) {
// tried changing to RedisException, didn't work either
// insert codes that'll deal with situations when connection to the redis server is not good
die( "Cannot connect to redis server:".$e->getMessage() );
}
$redis->setex('somekey', 60, 'some value');
但是当 Redis 服务器宕机时,我会收到以下信息:
PHP Fatal error: Uncaught exception 'RedisException' with message 'Redis server went away' in /var/www/2.php:10
Stack trace:
#0 /var/www/2.php(10): Redis->setex('somekey', 60, 'some value')
#1 {main}
thrown in /var/www/2.php on line 10
代码中catch块没有被执行。我回去阅读了phpredis文档,提出了以下解决方案。
<?php
$redis=new Redis();
$connected= $redis->connect('127.0.0.1', 6379);
if(!$connected) {
// some other code to handle connection problem
die( "Cannot connect to redis server.\n" );
}
$redis->setex('somekey', 60, 'some value');
我可以接受这个结果,但是我的好奇心永远无法得到满足,所以我有一个问题:为什么 try/catch 方法在连接错误时不起作用?
$redis->connect();
如果连接失败,不会抛出异常。你可以检查$redis===true
,如果为真则表示已连接,否则表示未连接。但正如 Nicolas 在下面指出的,上面的异常是来自 setex,因此除非将其放在 try catch 块中,否则无法捕获。 - Haluk