美文网首页
laravel 请求缓存中间件 加快响应速度

laravel 请求缓存中间件 加快响应速度

作者: aleshaw | 来源:发表于2020-08-18 12:15 被阅读0次

功能

  • 支持缓存渲染后数据
  • 支持指定缓存过期时间(默认10分钟)
  • header头输出缓存命中状态、缓存Key及过期时间
  • 支持定义tag,方便集中删除

/app/Http/Middleware/CacheResponse.php

<?php


namespace App\Http\Middleware;

use Carbon\Carbon;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;

/**
 * Response缓存中间件
 *
 */
class CacheResponse
{
    /**
     * @var \Illuminate\Http\Request
     */
    protected $request;

    /**
     * @var \Closure
     */
    protected $next;

    /**
     * 缓存分钟
     *
     * @var int|null
     */
    protected $minutes;

    /**
     * 缓存数据
     *
     * @var array
     */
    protected $responseCache;

    /**
     * 缓存命中状态,1为命中,0为未命中
     *
     * @var int
     */
    protected $cacheHit = 1;

    protected $tag = 'routeCache';

    /**
     * 缓存Key
     *
     * @var string
     */
    protected $cacheKey;

    /**
     * Handle an incoming request
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     * @param int|null                 $minutes
     * @param string|null                 $tag
     *
     * @return mixed
     */
    public function handle($request, Closure $next, $minutes = null, $tag = null)
    {
        $this->prepare($request, $next, $minutes, $tag);

        $this->responseCache();

        $response = response($this->responseCache['content']);

        return $this->addHeaders($response);
    }

    /**
     * 预备
     *
     * @return mixed
     */
    protected function prepare($request, Closure $next, $minutes = null, $tag = null)
    {
        $this->request = $request;
        $this->next = $next;
        $this->tag = $tag ?: 'routeCache';

        // 初始化值
        $this->cacheKey = $this->resolveKey();
        $this->minutes = $this->resolveMinutes($minutes);
    }

    /**
     * 生成或读取Response-Cache
     *
     * @return array
     */
    protected function responseCache()
    {
        $this->responseCache = cache()->tags(array_merge(['routeCache'], [$this->tag]))->remember(
            $this->cacheKey,
            $this->minutes * 60,
            function () {
                $this->cacheMissed();

                $response = ($this->next)($this->request);

                return $this->resolveResponseCache($response) + [
                        'cacheExpireAt' => Carbon::now()->addMinutes($this->minutes)->format('Y-m-d H:i:s T'),
                    ];
            }
        );

        return $this->responseCache;
    }

    /**
     * 确定需要缓存Response的数据
     *
     * @param \Illuminate\Http\Response $response
     *
     * @return array
     */
    protected function resolveResponseCache($response)
    {
        return [
            'content' => $response->getContent(),
        ];
    }

    /**
     * 追加Headers
     *
     * @param mixed
     */
    protected function addHeaders($response)
    {
        $response->headers->add(
            $this->getHeaders()
        );

        return $response;
    }

    /**
     * 返回Headers
     *
     * @return array
     */
    protected function getHeaders()
    {
        $headers = [
            'X-Cache' => $this->cacheHit ? 'Hit from cache' : 'Missed',
            'X-Cache-Key' => $this->cacheKey,
            'X-Cache-Expires' => $this->responseCache['cacheExpireAt'],
        ];

        return $headers;
    }

    /**
     * 根据请求获取指定的Key
     *
     * @return string
     */
    protected function resolveKey()
    {
        return md5($this->request->url().Arr::query($this->request->input()));
    }

    /**
     * 获取缓存的分钟
     *
     * @param int|null $minutes
     *
     * @return int
     */
    protected function resolveMinutes($minutes = null)
    {
        return is_null($minutes)
            ? $this->getDefaultMinutes()
            : max($this->getDefaultMinutes(), intval($minutes));
    }

    /**
     * 返回默认的缓存时间(分钟)
     *
     * @return int
     */
    protected function getDefaultMinutes()
    {
        return 10;
    }

    /**
     * 缓存未命中
     *
     * @return mixed
     */
    protected function cacheMissed()
    {
        $this->cacheHit = 0;
    }
}

配置

\app\Http\Kernel.php文件中$routeMiddleware增加:

<?php
'cacheResponse' => \app\Http\Middleware\CacheResponse::class,

// cacheResponse 命名随意,你开心就好

使用

<?php
Route::get('/', function () {
    return view('welcome');
})->middleware('cacheResponse'); //名称和上面保持一致

Route::get('/', function () {
    return view('welcome');
})->middleware('cacheResponse:20');  // 指定缓存时间20分钟

Route::get('/', function () {
    return view('welcome');
})->middleware('cacheResponse:20,tag');  // 指定缓存标签'tag'

删除

<?php
cache()->tags(['routeCache'])->flush(); //删除全部路由缓存
cache()->tags(['tag'])->flush(); //删除标签tag的路由缓存

相关文章

  • laravel 请求缓存中间件 加快响应速度

    功能 支持缓存渲染后数据 支持指定缓存过期时间(默认10分钟) header头输出缓存命中状态、缓存Key及过期时...

  • 网站慢优化

    静态资源:gzip(压缩静态资源加快响应速度) expires(缓存到客户端,减少http请求)cdn(缓存到客户...

  • 浏览器缓存机制

    浏览器会把一些重复请求的数据保存在缓存中,可以很好的加快请求响应速度,提高了用户体验,但是一些情况下又会缓存已经过...

  • Laravel学习笔记-中间件

    Laravel 中间件是什么? 简而言之,中间件在 laravel 中的作用就是过滤 HTTP 请求,根据不同的请...

  • Laravel 文档阅读:中间件

    简介 中间件用来过滤项目中的 HTTP 请求,实际上 Laravel 项目中大量使用了中间件。例如,Laravel...

  • 64. 中间件

    Laravel 中间件提供了一种方便的机制来过滤进入应用的 HTTP 请求。 Laravel 自带了一些中间件,包...

  • HTTP缓存

    http缓存:存储与请求关联的响应,并将存储的响应复用与后续请求 http缓存的好处: 响应速度快 减轻服务器的压...

  • springboot使用caffeine

    在系统中,有些数据,访问十分频繁,往往把这些数据放入分布式缓存中,但为了减少网络传输,加快响应速度,缓存分布式缓存...

  • django项目中使用 memcached (安装与使用)

    在django 中,如果你想提升请求的响应速度,那么使用缓存是很好的办法。django的官网上介绍了如何引入缓存,...

  • Laravel 中的面试题(一)

    1、什么是http中间件? HTTP中间件是一种用于过滤HTTP请求的技术。Laravel包含一个中间件,用 于检...

网友评论

      本文标题:laravel 请求缓存中间件 加快响应速度

      本文链接:https://www.haomeiwen.com/subject/grwhjktx.html