如何在Laravel 5.4中检查Redis连接的可用性。我试过下面的代码,但用ping行获得异常。我怎么办,如果没有连接Redis而不是做其他事情以避免异常?
无法建立连接,因为目标计算机主动拒绝它。 [TCP://127.0.0.1:6379]
use Redis;
class SocketController extends Controller
{
public function sendMessage(){
$redis = Redis::connection();
if($redis->ping()){
print_r("expression");
}
else{
print_r("expression2");
}
}
}
还试过这个:
$redis = Redis::connection();
try{
$redis->ping();
} catch (Exception $e){
$e->getMessage();
}
但无法捕捉异常
如果你使用的是predis,那么它会抛出Predis\Connection\ConnectionException
从服务器读取行时出错。 [tcp://127.0.0.1:6379] < - 未连接redis时
所以赶上那个例外,你会得到你的redis连接与否。
use Illuminate\Support\Facades\Redis;
public function redis_test(Request $request){
try{
$redis=Redis::connect('127.0.0.1',3306);
return response('redis working');
}catch(\Predis\Connection\ConnectionException $e){
return response('error connection redis');
}
确保安装了redis
$ sudo apt-get update
$ sudo apt-get upgrade
$ sudo apt-get install redis-server
要测试您的服务是否正常运行,请使用命令行客户端连接到Redis服务器:
redis-cli
在随后的提示中,键入以下内容来测试连接:
ping
你应该看到:
产量
PONG
安装Laravel依赖项
composer require predis/predis
https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-redis-on-ubuntu-16-04
https://askubuntu.com/questions/868848/how-to-install-redis-on-ubuntu-16-04
在构造函数中,您可以像这样检查redis状态连接:
/**
* RedisDirectGeoProximity constructor.
* @throws RedisConnectionException
*/
public function __construct()
{
try
{
$this->redisConnection = Redis::connection('default');
}
catch ( Exception $e )
{
throw new RedisConnectionException([
'message' => trans('messages.redis.fail'),
'code' => ApiErrorCodes::REDIS_CONNECTION_FAIL
]);
}
}
在你的例外中:
namespace App\Exceptions\Redis;
/**
* Class RedisConnectionException
* @package App\Exceptions\Redis
*/
class RedisConnectionException extends \Exception
{
/**
* RedisConnectionException constructor.
* @param array $options
*/
public function __construct(array $options = [])
{
parent::__construct($options);
}
}
<?php
namespace App\Helpers;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
class ConnectionChecker
{
public static function isDatabaseReady($connection = null)
{
$isReady = true;
try {
DB::connection($connection)->getPdo();
} catch (\Exception $e) {
$isReady = false;
}
return $isReady;
}
public static function isRedisReady($connection = null)
{
$isReady = true;
try {
$redis = Redis::connection($connection);
$redis->connect();
$redis->disconnect();
} catch (\Exception $e) {
$isReady = false;
}
return $isReady;
}
}
我创建了一个帮助类来检查redis和db连接
请尝试使用catch (\Exception $e)
incl。反斜线