我通过phpredis使用redis作为缓存商店。它工作得很好,我想提供一些自动防故障方法,以确保缓存功能始终正常(例如,使用基于文件的缓存),即使redis服务器出现故障,最初我想出了以下代码
$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文档并提出了以下解决方案
$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方法不能解决连接错误?