我通过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 10catch块的代码没有执行。我重新阅读了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方法不能处理连接错误?
发布于 2012-03-27 17:02:02
您的异常是从位于try {}块之外的setex发送的。将setex放在try块中,就会捕捉到异常。
发布于 2012-03-29 02:29:44
正如Nicolas所说,异常来自setex,但是您可以通过使用ping命令来避免这种情况(甚至是try/catch块):
$redis=new Redis();
$redis->connect('127.0.0.1', 6379);
if(!$redis->ping())
{
die( "Cannot connect to redis server.\n" );
}
$redis->setex('somekey', 60, 'some value');发布于 2019-04-24 16:06:42
如果你捕获'\Predis\ connection \ConnectionException‘,它将能够捕获连接异常。
https://stackoverflow.com/questions/9881133
复制相似问题