为什么Try / Catch在phpredis连接功能中不起作用?

问题描述 投票:7回答:3

我通过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 try-catch
3个回答
4
投票

您的例外是从setex发送的,它位于try {}块之外。将setex放在try块中,将捕获异常。


1
投票

正如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');

0
投票

如果你捕获'\ Predis \ Connection \ ConnectionException',它将能够捕获连接异常。

或者您可以使用\ Exception而不是Exception(注意前面的正斜杠)。

© www.soinside.com 2019 - 2024. All rights reserved.