简体   繁体   English

Laravel中间件缓存无法正常工作

[英]Laravel Middleware Cache not working properly

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. 我正在尝试创建中间件,该中间件将检查指定服务器的状态并将此状态放到Cache中,但是由于在尝试检查键的存在等情况下给定的缓存值始终为null,因此缓存无法在中间件中正常工作。

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. 众所周知,$ this-> checkServerStatus()返回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"). 因此,当我尝试检查Cache键是否存在时,对于Cache :: has(“ KEY”)始终为false,对于Cache :: get(“ KEY”)始终为null。

What's wrong? 怎么了? I cannot use cache in Middleware? 我不能在中间件中使用缓存?

The behaviour of Cache::has method relies a lot in the actual backend you're using. Cache :: has方法的行为在很大程度上取决于您所使用的实际后端。

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. 例如,您可以使用-vv启动memcached以查看获取和设置,或者可以连接到Redis实例并执行MONITOR来查看应用程序的工作。 This might help you spot the issue. 这可以帮助您发现问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM