Skip to content

Commit

Permalink
fix: catch redis unavailable error and fallback to default cache
Browse files Browse the repository at this point in the history
  • Loading branch information
pifou25 committed Jun 23, 2024
1 parent 3934d23 commit ed257c4
Showing 1 changed file with 27 additions and 15 deletions.
42 changes: 27 additions & 15 deletions core/class/cache.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,25 +96,30 @@ public static function stats($_details = false) {
* @name getCache()
* @access public
* @static
* @param string $_engine to override the current cache defined in configuration
* @return \Doctrine\Common\Cache\CacheProvider
*/
public static function getCache() {
if (self::$cache !== null) {
public static function getCache($_engine = null) {
if ($_engine === null && self::$cache !== null) {
return self::$cache;
}
$engine = config::byKey('cache::engine');
if( $_engine === null){
// get current cache
$engine = config::byKey('cache::engine');
}else{
// override existing configuration
$engine = $_engine;
config::save('cache::engine', $_engine);
}
// check if memcached extention is available
if ($engine == 'MemcachedCache' && !class_exists('memcached')) {
$engine = 'FilesystemCache';
config::save('cache::engine', 'FilesystemCache');
return self::getCache( 'FilesystemCache');
}
// check if redis extension is available
if ($engine == 'RedisCache' && !class_exists('redis')) {
$engine = 'FilesystemCache';
config::save('cache::engine', 'FilesystemCache');
return self::getCache( 'FilesystemCache');
}
switch ($engine) {
case 'FilesystemCache':
self::$cache = new \Doctrine\Common\Cache\FilesystemCache(self::getFolder());
break;
case 'PhpFileCache':
self::$cache = new \Doctrine\Common\Cache\FilesystemCache(self::getFolder());
break;
Expand All @@ -127,15 +132,22 @@ public static function getCache() {
case 'RedisCache':
$redis = new Redis();
$redisAddr = config::byKey('cache::redisaddr');
if (strncmp($redisAddr, '/', 1) === 0) {
$redis->connect($redisAddr);
} else {
$redis->connect($redisAddr, config::byKey('cache::redisport'));
try{
// try to connect to redis
if (strncmp($redisAddr, '/', 1) === 0) {
$redis->connect($redisAddr);
} else {
$redis->connect($redisAddr, config::byKey('cache::redisport'));
}
}catch( Exception $e){
// error : fall back to FilesystemCache
log::add( __CLASS__, 'error', 'Unable to connect to redis instance, fall back to FilesystemCache.'."\n".$e->getMessage());
return self::getCache( 'FilesystemCache');
}
self::$cache = new \Doctrine\Common\Cache\RedisCache();
self::$cache->setRedis($redis);
break;
default:
default: // default is FilesystemCache
self::$cache = new \Doctrine\Common\Cache\FilesystemCache(self::getFolder());
break;
}
Expand Down

0 comments on commit ed257c4

Please sign in to comment.