Home » Php » php – Default to Laravel File cache if redis is down

php – Default to Laravel File cache if redis is down

Posted by: admin July 12, 2020 Leave a comment

Questions:

In the spirit of “chaos monkey” I’m trying to ensure that a laravel application keeps going even when the services it depends on are down.

It uses a DB for primary storage, and a redis cache. What I’d like to do is have it automatically fall back to the file cache if and when redis fails.

I haven’t been able to find a clear example.

How to&Answers:

One way to solve this problem is to overwrite Laravel’s default Illuminate\Cache\CacheManagerclass and alter the ioc binding

class MyCacheManager extends Illuminate\Cache\CacheManager
{
    protected function createRedisDriver(array $config)
    {
        try {
            return parent::createRedisDriver($config);
        } catch (\Exception $e) {
            //Error with redis
            //Maybe there is a more explicit exception ;)
            return $this->resolve('file');
        }
    }
}

In some ServiceProvider

$this->app->singleton('cache', function($app)
{
    return new MyCacheManager($app);
});

This solution will also keep the Cache facade working 🙂

Answer:

There seems to be a package exactly for this:
https://github.com/xtcat/laravel-redis-fallback

I haven’t yet found similar packages for Sessions or Queues. Please share here if anybody has.

Answer:

Can you not just include an anonymous function in place of the cache driver cnfig setting?

that could try to use Redis and if it fails return file as the setting and Redis if it succeeds