GuzzleHttp和Memcached的关键

问题描述 投票:0回答:2

我玩弄了GuzzleHttp客户端,GuzzleCacheMiddleware和Memcached的。

该设置是调用不同的参数相同的URL。

这导致了一个! memcached的打击,所以我觉得memcached的关键是从URL和唯一的URL创建。

我能以某种方式改变这种行为,所以关键包括参数的MD5?

php memcached guzzle
2个回答
0
投票

你必须创建自己的CacheStrategy类。例如,你可以扩展PrivateCacheStrategy类并覆盖getCacheKey方法,负责创建缓存键。

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

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


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的。我也允许被缓存的HTTP POST方法,因为默认情况下只得到被缓存!

$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'));
}
© www.soinside.com 2019 - 2024. All rights reserved.