【发布时间】:2019-04-24 16:06:41
【问题描述】:
我通过 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 是否为 true,如果为 true,则您已连接,否则您未连接。但正如 Nicolas 在下面指出的,上面的异常来自 setex,因此除非你将它放在 try catch 块中,否则它不会被捕获。 -
@haluk Redis 连接方法抛出异常。