V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
raysonlu
V2EX  ›  PHP

PHP 如何连接 redis 失败后不报错跳过继续执行代码?

  •  
  •   raysonlu · Jul 25, 2018 · 5549 views
    This topic created in 2834 days ago, the information mentioned may be changed or developed.

    项目某部分缓存想使用 redis 部署,默认是使用文件缓存的,但不确保 redis 服务是否正常连接,希望检测到 redis 连接不成功则自动切换到文件缓存,有什么方法?

    php 去连接 redis 服务器,发现连接不成功就直接给出致命错误中止代码运行了,try{}cahtch()无法捕捉致命错误

    10 replies    2018-08-24 09:45:54 +08:00
    update
        1
    update  
       Jul 25, 2018
    使用的什么 redis 类库? 看是不是类库里面直接报错了。
    sorshion
        2
    sorshion  
       Jul 25, 2018
    php7 试试 try{}catch(\Error $e){}
    sparrww
        3
    sparrww  
       Jul 25, 2018
    为什么捕捉不到,尝试了吗
    vus520
        4
    vus520  
       Jul 25, 2018
    原生的 Redis 类,所有异常都是可以捕获的。
    DavidNineRoc
        5
    DavidNineRoc  
       Jul 25, 2018
    不上截图一律按照自己的代码问题处理,
    如果用 predis,有连接失败的异常 https://github.com/phpredis/phpredis/#class-redisexception
    > phpredis throws a RedisException object if it can't reach the Redis server. That can happen in case of connectivity issues, if the Redis service is down, or if the redis host is overloaded. In any other problematic case that does not involve an unreachable server (such as a key not existing, an invalid command, etc), phpredis will return FALSE.
    caola
        6
    caola  
       Jul 25, 2018
    php7 试试 try{}catch(\Error $e){}  +1
    dobelee
        7
    dobelee  
       Jul 25, 2018
    set_error_handler()

    try {}
    catch(\ErrorException $e) {}
    catch(\Exception $e) {}

    了解一下,捕捉一切异常。
    spkinger
        8
    spkinger  
       Jul 25, 2018
    还有一个 Throwable,
    这个也可以尝试 catch 下
    raysonlu
        9
    raysonlu  
    OP
       Jul 25, 2018
    哈哈,小弟问题,确实能捕捉了!原来是框架问题,没有在初始化的时候连接 redis,所以我在那儿 try catch 总是没有反应,哈哈。谢谢各位大神了!
    ksharp8
        10
    ksharp8  
       Aug 24, 2018
    行前加 @或者首行加 error 类代码,或者 php.ini 调整报错等级
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5630 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 44ms · UTC 07:09 · PVG 15:09 · LAX 00:09 · JFK 03:09
    ♥ Do have faith in what you're doing.