Skip to content

Commit 7527bac

Browse files
committed
增加header头输出缓存命中状态、缓存key、缓存失效时间
1 parent 71ab863 commit 7527bac

File tree

1 file changed

+27
-4
lines changed

1 file changed

+27
-4
lines changed

src/Middleware/CacheResponse.php

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use Illuminate\Http\Request;
66
use Illuminate\Http\Response;
7+
use Carbon\Carbon;
78
use Closure;
89
use Cache;
910

@@ -22,6 +23,20 @@ class CacheResponse
2223
*/
2324
protected $cache_hit = 1;
2425

26+
/**
27+
* 缓存Key
28+
*
29+
* @var string
30+
*/
31+
protected $cache_key;
32+
33+
/**
34+
* 缓存失效时间
35+
*
36+
* @var string
37+
*/
38+
protected $cache_expire_at;
39+
2540
/**
2641
* Handle an incoming request.
2742
*
@@ -48,15 +63,21 @@ public function handle($request, Closure $next, $minutes = null)
4863
*/
4964
protected function getResponseCache($request, $next, $minutes)
5065
{
51-
$key = $this->resolveRequestKey($request);
66+
$this->cache_key = $key = $this->resolveRequestKey($request);
5267

53-
return Cache::remember($key, $this->resolveMinutes($minutes), function () use ($request, $next) {
68+
$responseCache = Cache::remember($key, $resolveMinutes = $this->resolveMinutes($minutes), function () use ($request, $next, $resolveMinutes) {
5469
$this->cacheMissed();
5570

5671
$response = $next($request);
5772

58-
return $this->resolveResponseCache($response);
73+
return $this->resolveResponseCache($response) + [
74+
'cacheExpireAt' => Carbon::now()->addMinutes($resolveMinutes)->format('Y-m-d\TH:i:s')
75+
];
5976
});
77+
78+
$this->cache_expire_at = $responseCache['cacheExpireAt'];
79+
80+
return $responseCache
6081
}
6182

6283
/**
@@ -94,7 +115,9 @@ protected function addHeaders($response)
94115
protected function getHeaders()
95116
{
96117
$headers = [
97-
'X-Cache-Hit' => $this->cache_hit,
118+
'X-Cache' => $this->cache_hit ? 'Hit' : 'Missed',
119+
'X-Cache-Key' => $this->cache_key,
120+
'X-Cache-ExpireAt' => $this->cache_expire_at,
98121
];
99122

100123
return $headers;

0 commit comments

Comments
 (0)