写了一个hyperf的路由的中间件来做通用缓存,有同学帮我看看,写的有问题不
写了一个hyperf的路由的中间件来做通用缓存,有同学帮我看看,写的有问题不
<?php
declare(strict_types=1);
namespace App\Middleware;
use Carbon\Carbon;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Hyperf\HttpServer\Router\Dispatched;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
/**
* 路由缓存中间件
* 例子:Router::get('/items/{item_id}', 'App\Controllers\ItemsController@itemsDetail', ['middleware' => [\App\Middleware\RouterCacheMiddleware::class], 'cache_enable' => true, 'cache_ttl' => 300]);
* cache_enable如果不配置则是开启状态,cache_ttl如果不配置就是取默认的ttl
*
*/
class RouterCacheMiddleware implements MiddlewareInterface
{
/**
* 缓存开启状态,默认开启.
* @var bool
*/
protected $enabled = true;
/**
* 缓存时间[单位是秒], 默认60秒.
* @var int 秒
*/
protected $ttl = 60;
/**
* @var HttpResponse
*/
protected $response;
public function __construct(HttpResponse $response)
{
$this->response = $response;
}
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
if (strtoupper($request->getMethod()) != 'GET') {
return $handler->handle($request);
}
$dispatched = $request->getAttribute(Dispatched::class);
$cache_enable = $this->getEnabled($dispatched->handler->options['cache_enable'] ?? null);
$cache_ttl = $this->getTTL($dispatched->handler->options['cache_ttl'] ?? null);
if (config('router_cache_enable') && $cache_enable) {
$cacheKey = $this->getCacheKey($request);
$cache = cache('default')->get($cacheKey);
if ($cache) {
$cachedData = json_decode($cache, true);
return $this->response->json(json_decode($cachedData['contents']))
->withHeader('X-cache', 'Hit')
->withHeader('X-Cache-Key', $cacheKey)
->withHeader('X-Cache-Expires', $cachedData['expireAt']);
}
$response = $handler->handle($request);
$cacheData = [
'contents' => $response->getBody()->getContents(),
'expireAt' => Carbon::now()->addSeconds($cache_ttl)->format('Y-m-d H:i:s T'),
];
// if ($cacheData['contents']['errcode'] == 0) {
cache('default')->set($cacheKey, json_encode($cacheData), $cache_ttl);
// }
$response = $response->withHeader('X-cache', 'Missed');
return $response;
}
return $handler->handle($request);
}
protected function getCacheKey(ServerRequestInterface $request)
{
return md5('pages:' . sprintf('%s?%s', $request->getUri()->getPath(), http_build_query($request->getQueryParams())));
}
/**
* 获取缓存时间.
*
* @param null|int $seconds
*
* @return int
*/
protected function getTTL($seconds = null)
{
return is_null($seconds) ? $this->ttl : intval($seconds);
}
/**
* 获取缓存开启状态.
*
* @param null|bool $cache_enabled
*
* @return bool
*/
protected function getEnabled($cache_enabled = null)
{
return is_null($cache_enabled) ? $this->enabled : $cache_enabled;
}
}
本作品采用《CC 协议》,转载必须注明作者和本文链接