Symfony REST API的响应缓存

时间:2018-01-24 15:29:54

标签: json rest symfony caching fosrestbundle

我有一个使用FOSREST Bundle的REST API。响应由JMS Bundle序列化。现在我想缓存一些响应,因为序列化需要相当长的时间。我想在序列化后存储响应数据,然后,如果数据库没有更改,则提供缓存的响应,而不是再次进行序列化。任何想法如何实现这一目标?

更具体一点: 我有一个控制器,它输出大量数据,大部分时间都没有变化。由于序列化需要几秒钟,我想加快速度 使用缓存的输出。

我想我需要设置一个事件" afterSerialization"写缓存。 但是因为fosrestBundle被配置为序列化视图处理的所有数据,所以我找不到输出预序列化数据的方法,而无需再次发送到序列化器。

public function postProductsAction(Request $request)
{

    $em = $this->get('doctrine')->getManager();

    // TODO check if db is unchanged and cache exists
    // if check is true stop here and redirect to cached json response

    $products = $em->getRepository('PPApiBundle:Produkte')->findBy(array("status" => 1));

    $data = array(
      "data" => $products,
      "opt" => array()
    );

    $view = $this->view($data, 200);
    $ret = $this->handleView($view);

    // TODO cache json string after serialization 

    return $ret

}

1 个答案:

答案 0 :(得分:0)

您可以使用doctrine查询构建器的查询缓存和响应缓存方法在序列化之前缓存结果。

->getQuery()->useQueryCache(true)->useResultCache(true, 3600)
相关问题