在使用redis之前我想检查它的可用性,如果redis不可用,我将使用mysql,如果redis可用,我将使用它.如果我使用predis客户端,我该怎么办呢?
我的第一种方法是:
/**
* @return bool
*/
public function check(){
if(!@fsockopen ( $server['host'], $server['port'], $errno, $errstr, 3 )){
Debug::instance()->log( 'Redis connect error host: ' . $server['host'] . ' port: ' . $server['port'] );
return false;
}
return true;
}
但这是一个非常糟糕的主意,因为我占用了免费套接字.现在我试着找到一个更好的方法.
解决方法:
这应该做的伎俩;)
// Redis configuration
$vm = array(
'host' => '127.0.0.1',
'port' => 6379,
'timeout' => 0.8 // (expressed in seconds) used to connect to a Redis server after which an exception is thrown.
);
$redis = new Predis\Client($vm);
try {
$redis->ping();
} catch (Exception $e) {
// LOG that redis is down : $e->getMessage();
}
if(isset($e)) {
//use MySQL
} else {
/* Use Redis */
}
标签:php,redis
来源: https://codeday.me/bug/20190718/1492661.html