douweng1935 2016-06-21 15:28
浏览 211

Laravel Middleware Cache无法正常工作

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?

  • 写回答

1条回答 默认 最新

  • doujumiao5024 2016-06-21 18:53
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 python变量和列表之间的相互影响
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)