Symfony2 : ESI setMaxAge Cache

标签 symfony caching esi

我有一个 Controller ,其操作在 Twig 中呈现

{{ render_esi(controller('MyWebsiteBundle:Element:header')) }}

操作本身如下所示:

/**
     * @return Response
     */
    public function headerAction()
    {
        $currentLocale = $this->getCurrentLocale();

        $response = $this->render('MyWebsiteBundle:Element:header.html.twig', array(
            'currentLocale' => $currentLocale,
            'myTime' => time()
        ));
        $response->setPublic();
        $response->setSharedMaxAge(3600);

        return $response;
    }

当我重新加载浏览器时,“myTime”每次都会改变。

如何使用setShardeMaxAge(),以便仅在 MaxAge 过期后渲染 Twig?

最佳答案

在 Symfony2 中,您需要执行一些操作才能激活 esi 缓存。

1) 在 app/config/config.yml 中确保您激活了 esi,并带有片段路径。

framework:
    esi: { enabled: true }
    fragments: { path: /_proxy }

2) 用AppCache对象包装内核

// web/app.php
$kernel = new AppCache($kernel); 

3) 设置AppCache配置

// app/AppCache.php
use Symfony\Bundle\FrameworkBundle\HttpCache\HttpCache;

class AppCache extends HttpCache
{
    protected function getOptions()
    {
        return array(
            'debug'                  => false,
            'default_ttl'            => 0,
            'private_headers'        => array('Authorization', 'Cookie'),
            'allow_reload'           => false,
            'allow_revalidate'       => false,
            'stale_while_revalidate' => 2,
            'stale_if_error'         => 60,
        );
    }
}

关于您的问题,如果它正在缓存您的响应,唯一的问题是它会在您每次刷新页面时重新加载。确保配置 allow_reload 属性设置为 false。

您可以在这里阅读更多相关信息: http://symfony.com/doc/current/book/http_cache.html

关于Symfony2 : ESI setMaxAge Cache,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30614573/

相关文章:

mysql - Symfony2 多对多与 COUNT

php - 在 symfony2 表单中设置日期时间字段的默认值

mysql - Symfony 中的数据库连接错误

c# - 如何清除 System.Runtime.Caching.MemoryCache

symfony - 登录 ESI 组件中的缓存页面会重定向到/_internal/secure/.../none.html

forms - symfony2文本字段自定义标签

browser - 如何从服务器端清除浏览器的缓存?

android - ListView 滞后;缓存文件有问题吗?

php - Symfony2 ESI : Responses marked as public, 即使子请求包含私有(private)响应