【问题标题】:Laravel Middleware Cache not working properlyLaravel 中间件缓存无法正常工作
【发布时间】:2016-06-22 02:53:18
【问题描述】:

我正在尝试创建将检查指定服务器的状态并将此状态放入缓存的中间件,但缓存在中间件中无法正常工作,当我尝试检查密钥时缓存值始终为空存在等等。

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;
}

请注意,$this->checkServerStatus() 返回 true/false。

因此,当我尝试检查缓存键是否存在时,Cache::has("KEY") 始终为 false 或 Cache::get("KEY") 为 null。

怎么了?我不能在中间件中使用缓存?

【问题讨论】:

    标签: php arrays laravel caching laravel-middleware


    【解决方案1】:

    Cache::has 方法的行为很大程度上依赖于您正在使用的实际后端。

    尝试这样做:

    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;
    }
    

    这样你就不会在缓存中存储一​​个布尔值,而是一个字符串。也许这不是解决方案,但会为您指明正确的方向。

    根据您使用的缓存引擎,您可能希望在调试模式下启动它以查看正在执行的连接和事务。例如,您可以使用 -vv 启动 memcached 以查看获取和设置,或者您可以连接到 Redis 实例并执行 MONITOR 以查看您的应用程序做了什么。这可能会帮助您发现问题。

    【讨论】:

    • 感谢您的回复,但问题已通过将缓存驱动程序从阵列更改为redis解决。我只是不记得我出于某些调试目的选择了第一个 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-22
    • 2019-11-24
    相关资源
    最近更新 更多