Laravel使用Midderware完成整页缓存

2017-08-21 19:06:39

    以前一直使用一个叫page-cache的包,来生成静态的html文件,在nginx中rewrite指向,使网站打开速度飞快。

    但是随着页面复杂化发后,发现此功能越来越不能满足需求了,现在只能送它两个字:爱过!

    现在我们使用redis制作一个中间层,把页面响应内容保存起来,以当前的url为键储存起来,从而实现整站缓存的目的。使一此比较复杂的应用都能共享此功能,从而给网站提速。

    首先我们要在控制台生成相应的 midderware

php artisan make:middleware CachePage

    然后在此文件中,写入如下代码:

<?php

namespace App\Http\Middleware;

use Closure;
use Cache;

class CachePage
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $key = $request->fullUrl();  //key for caching/retrieving the response value

        if (Cache::has($key))  //If it's cached...
            return response(Cache::get($key));   //... return the value from cache and we're done.

        $response = $next($request);  //If it wasn't cached, execute the request and grab the response

        $cachingTime = 60;  //Let's cache it for 60 minutes
        Cache::put($key, $response->getContent(), $cachingTime);  //Cache response

        return $response;
    }
}

    下一步当然要去app\Http\Kernel.php中去注册一下啦,在$routeMiddleware数组中加入,

'cachepage' => \App\Http\Middleware\CachePage::class,

    至此,整页缓存中间键就已经搞好了,使用只需同要路由中指定

'middleware' => 'cachepage'

    就可以啦。