0

I'm trying to create middleware which will check status of specified server and put this status to the Cache, but the cache is not working in middleware properly, given cache value is always null when I'm trying to check the key existence etc.

public function handle($request, Closure $next)
{
    $response = $next($request);

    if(!Cache::has(Config::get('ots.server_status_cache_name'))) {
        if($this->checkServerStatus()) {
            Cache::put(Config::get('ots.server_status_cache_name'), 1, Config::get('ots.server_status_cache_time'));
        } else {
            Cache::put(Config::get('ots.server_status_cache_name'), 0, Config::get('ots.server_status_cache_time'));
        }
    }

    return $response;
}

Just for your know, $this->checkServerStatus() returns true/false.

So, when I'm trying to check Cache key existance, it's always false for Cache::has("KEY") or null for Cache::get("KEY").

What's wrong? I cannot use cache in Middleware?

Narkon
  • 398
  • 2
  • 17

1 Answers1

0

The behaviour of Cache::has method relies a lot in the actual backend you're using.

Try doing this:

public function handle($request, Closure $next)
{
    $response = $next($request);

    if(Cache::has(Config::get('ots.server_status_cache_name'))) {
        return $response; // Exit method as soon as you can
    }

    $serverStatus = $this->checkServerStatus() ? 'up' : 'down';
    Cache::put(Config::get('ots.server_status_cache_name'), $serverStatus, Config::get('ots.server_status_cache_time'));

    return $response;
}

In that way you don't store a boolean in cache, but a string. Maybe this is not the solution, but will point you in the right direction.

Depending on the caching engine you use, you might want to start it in debug mode to see the connections and transactions being executed. For example, you can start memcached with -vv to see gets and sets, or you can connect to the Redis instance and execute MONITOR to see what your application does. This might help you spot the issue.

Nico Andrade
  • 880
  • 5
  • 16
  • Thanks for reply, but problem was solved by changing the cache driver from array to redis. I just didn't remember that I selected the first one for some debug purposes :) – Narkon Jun 21 '16 at 19:04