GuzzleHttp和Memcached键

时间:2019-02-07 11:27:21

标签: php memcached guzzle

我正在玩GuzzleHttp客户端,GuzzleCacheMiddleware和Memcached。

设置正在使用不同的参数调用相同的网址。

结果为一! memcached命中,所以我认为memcached密钥是从url和仅url创建的。

我可以以某种方式更改此行为,因此键包含参数的md5吗?

2 个答案:

答案 0 :(得分:0)

您将必须创建自己的CacheStrategy类。例如,您可以扩展PrivateCacheStrategy类并重写getCacheKey方法,该方法负责创建缓存键。

https://github.com/Kevinrob/guzzle-cache-middleware/blob/master/src/Strategy/PrivateCacheStrategy.php#L123

您是对的,它仅基于URL和请求方法创建存储密钥。

答案 1 :(得分:0)

决定进行调查。没错,它需要GreedyCacheStrategy,因为它实际上可以缓存所有内容,而不管任何RFC标准如何。

用于创建缓存键的自定义类。

class ParamsGreedyCacheStrategy extends GreedyCacheStrategy
{
    /**
     * Ignoring any headers, just straight up cache key based on method, URI, request body/params
     *
     * @param RequestInterface $request
     * @param KeyValueHttpHeader|null $varyHeaders
     * @return string
     */
    protected function getCacheKey(RequestInterface $request, KeyValueHttpHeader $varyHeaders = null)
    {
        return hash(
            'sha256',
            'greedy' . $request->getMethod() . $request->getUri() . $request->getBody()
        );
    }
}

创建请求。我在这里使用了Laravel缓存,可以使用memcached。我还允许缓存POST HTTP方法,因为默认情况下仅缓存GET!

$handlerStack = HandlerStack::create();

$cacheMiddleware = new CacheMiddleware(
    new ParamsGreedyCacheStrategy(
        new LaravelCacheStorage(
            Cache::store('file')
        ),
        10
    )
);

// Not documented, but if you look at the source code they have methods for setting allowed HTTP methods. By default, only GET is allowed (per standards).
$cacheMiddleware->setHttpMethods(['GET' => true, 'POST' => true]);

$handlerStack->push(
    $cacheMiddleware,
    'cache'
);

$client = new Client([
    'base_uri' => 'https://example.org',
    'http_errors' => false,
    'handler' => $handlerStack
]);


for($i = 0; $i < 4; $i++) {
    $response = $client->post('/test', [
        'form_params' => ['val' => $i]
    ]);
    // Middleware attaches 'X-Kevinrob-Cache' header that let's us know if we hit the cache or not!
    dump($response->getHeader('X-Kevinrob-Cache'));
}