duanqianhuan3994 2016-05-22 18:35
浏览 71
已采纳

PHP:Guzzle 6 + Guzzle-cache-middleware

I've a page doing some REST queries using Guzzle 6. It works fine, however sometimes it gets to slow because it's always making queries. I found out that there is guzzle-cache-middleware that is supposed to cache responses from the remote API.

However I can't get it to work, my code follows something like:

use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use League\Flysystem\Adapter\Local;
use Kevinrob\GuzzleCache\CacheMiddleware;
use Kevinrob\GuzzleCache\Strategy\PrivateCacheStrategy;
use Kevinrob\GuzzleCache\Storage\FlysystemStorage;

(...)

$stack = HandlerStack::create();
$stack->push(
  new CacheMiddleware(
    new PrivateCacheStrategy(
      new FlysystemStorage(
        new Local("/tmp/sitex")
      )
    )
  ), 
  "cache"
);


// Request
$client = new Client([
    "handler"  => $stack,
    "base_uri"  => "http://...,
    "timeout"   => 2.0,
]);

$response = $client->request("GET", "/posts", [
(...)

After running the code I don't get any errors or warnings. Guzzle still gives me the API response, however nothing new appear into /tmp/sitex.

Do I need to set anything after the request to cache the response? Are there options like setting the TTL of the responses?

The documentation doesn't explain any of this, so if someone experienced on Guzzle can help me it would be nice. :)

  • 写回答

1条回答 默认 最新

  • dongyi7901 2016-05-22 20:45
    关注

    I managed to fix this by replacing $stack->push( with:

    $stack->push(
          new CacheMiddleware(
            new GreedyCacheStrategy(
              new FlysystemStorage(
                new Local("/tmp/sitex")
              ),
              180
            )
          ), 
          "cache"
        );
    
    • GreedyCacheStrategy: Always cache the response without checking it's headers for cache information;
    • 180 is the TTL we want to have the cache stored.

    Also replace use Kevinrob\GuzzleCache\Strategy\PrivateCacheStrategy; by use Kevinrob\GuzzleCache\Strategy\GreedyCacheStrategy;

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题