ApiPlatform-在提供程序操作中添加cacheHeaders
创始人
2024-09-08 02:00:29
0

要在ApiPlatform提供程序的操作中添加缓存头,您可以使用Symfony HTTP Cache组件中的CacheControl类。您可以通过在操作注释中使用@Cache控制器注释来自定义缓存头。例如:

use Symfony\Component\Cache\Adapter\FilesystemAdapter; use Symfony\Component\Cache\CacheItem; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; use Symfony\Contracts\Cache\CacheInterface; use ApiPlatform\Core\Serializer\SerializerContextBuilderInterface; use ApiPlatform\Core\Bridge\Symfony\Validator\Validator;

/**

  • @Route("/api/posts")

  • @Cache(public=true, maxage="600", smaxage="600") */ class PostController { private $serializerContextBuilder; private $validator; private $cache;

    public function __construct(SerializerContextBuilderInterface $serializerContextBuilder, Validator $validator, CacheInterface $cache) { $this->serializerContextBuilder = $serializerContextBuilder; $this->validator = $validator; $this->cache = $cache; }

    /**

    • @Route("/", methods={"GET"})

    • @param Request $request

    • @return Response */ public function index(Request $request): Response { $item = $this->cache->getItem('api_posts'); if (!$item->isHit()) { $posts = ... $item->set($posts); $this->cache->save($item); }

      return new Response($item->get(), 200, ['Content-Type' => 'application/json']); } }

在上面的示例中,我们在操作注释中添加了@Cache控制器注释,其中maxage和smaxage属性分别指定了缓存的最大年龄和共享缓存的最大年龄(如果存在)。在操作方法中,我们使用Symfony HTTP Cache组件中的CacheInterface将请求的结果缓存到文件系统中,然后将结果响应给客户端。

相关内容

热门资讯

推荐十款!七彩云南麻将有没有挂... 推荐十款!七彩云南麻将有没有挂(透视)本来是有挂(2022已更新)(哔哩哔哩)1、七彩云南麻将有没有...
wepokeai机器人!用ai... wepokeai机器人!用ai外 挂打德州有用(辅助挂)wepOke(本来真的有挂);一、wepOk...
微扑克辅助软件!微扑克超级统计... 您好,微扑克这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩家在这款游戏中...
揭秘!广东雀神麻将怎么让系统发... 揭秘!广东雀神麻将怎么让系统发好牌(透视)果然是真的有挂(2020已更新)(哔哩哔哩)1、进入到广东...
wepoke辅助挂!wepok... wepoke辅助挂!wepoke好友助力(透视辅助)WePoKer(一般真的有挂);WePoKer软...
微扑克有辅助挂!微扑克俱乐部,... 微扑克有辅助挂!微扑克俱乐部,微扑克ai人工智能,wepoke教程(有挂黑科技)1、微扑克ai机器人...
玩家攻略推荐!闽游麻将(透视辅... 玩家攻略推荐!闽游麻将(透视辅助)原来存在有挂(2023已更新)(哔哩哔哩);1、闽游麻将ai辅助优...
软件教程!wopoker轻量版... 软件教程!wopoker轻量版外 挂(wepoke辅助技巧)wepoKE(果然真的有挂)关于wopo...
微扑克ai辅助工具!微扑克辅助... 微扑克ai辅助工具!微扑克辅助多少钱,微扑克ai操作,可靠技巧(有挂ai代打);人气非常高,ai更新...
玩家科普!吉祥麻将怎么让系统发... 玩家科普!吉祥麻将怎么让系统发好牌(透视辅助)竟然存在有挂(2026已更新)(哔哩哔哩)亲,关键说明...