使用 Cloudflare 缓存 JSON

Posted

技术标签:

【中文标题】使用 Cloudflare 缓存 JSON【英文标题】:Caching JSON with Cloudflare 【发布时间】:2012-07-18 14:15:23 【问题描述】:

我正在为我在 Google App Engine 上的应用程序开发一个后端系统。

我的应用程序和后端服务器与 json 通信。喜欢http://server.example.com/api/check_status/3838373.json 或仅http://server.example.com/api/check_status/3838373/

我打算使用 CloudFlare 来缓存 JSON 页面。

我应该在页眉上使用哪一个? :

Content-type: application/json
Content-type: text/html

CloudFlare 是否缓存我的服务器响应以降低我的成本?因为我不会使用 CSS、图片等。

【问题讨论】:

【参考方案1】:

标准 Cloudflare 缓存级别(在您的域的性能设置下)设置为标准/激进,这意味着默认情况下它仅缓存某些类型 scripts, stylesheets, images。积极缓存不会缓存普通网页(即在目录位置或 *.html),也不会缓存 JSON。所有这些都基于 URL 模式(例如,它是否以 .jpg 结尾?)并且与 Content-Type 标头无关。

全局设置只能降低而不是更多,因此您需要设置一个或多个页面规则来匹配这些 URL,使用 Cache Everything 作为自定义缓存规则。

http://blog.cloudflare.com/introducing-pagerules-advanced-caching

顺便说一句,我不建议对 JSON 响应使用 HTML Content-Type。

【讨论】:

【参考方案2】:

默认情况下,Cloudflare 不缓存 JSON 文件。我最终配置了一个新的页面规则:

https:/domain.com/sub-directiory/*.json*
缓存级别:缓存所有内容 浏览器缓存 TTL:设置超时 边缘缓存 TTL:设置超时

希望它能拯救某人的一天。

【讨论】:

哇哦!!谢谢!【参考方案3】:

新的workers 功能(额外 5 美元)可以促进这一点:

重点: Cloudflare 通常将普通静态文件视为几乎永不过期(或者可能是一个月 - 我完全忘记了)。

所以一开始你可能会想到"I just want to add .json to the list of static extensions"。这可能不是你想要的 JSON - 除非它真的很少改变 - 或者由文件名版本控制。您可能需要 60 秒或 5 分钟,这样如果您更新文件,它会在这段时间内更新,但您的服务器不会受到来自每个最终用户的单独请求的轰炸。

以下是我如何让工作人员拦截所有 .json 扩展文件:

// Note: there could be tiny cut and paste bugs in here - please fix if you find!
addEventListener('fetch', event => 
  event.respondWith(handleRequest(event));
);

async function handleRequest(event)

  let request = event.request;
  let ttl = undefined;
  let cache = caches.default;      
  let url = new URL(event.request.url);

  let shouldCache = false;


  // cache JSON files with custom max age
  if (url.pathname.endsWith('.json'))
  
    shouldCache = true;
    ttl = 60;
  

  // look in cache for existing item
  let response = await cache.match(request);

  if (!response) 
         
    // fetch URL
    response = await fetch(request);

    // if the resource should be cached then put it in cache using the cache key
    if (shouldCache)
    
      // clone response to be able to edit headers
      response = new Response(response.body, response);

      if (ttl) 
      
        // https://developers.cloudflare.com/workers/recipes/vcl-conversion/controlling-the-cache/
        response.headers.append('Cache-Control', 'max-age=' + ttl);
      

      // put into cache (need to clone again)
      event.waitUntil(cache.put(request, response.clone()));
    

    return response;
  

  else 
    return response;
  

您可以使用 mime-type 而不是扩展名来执行此操作 - 但这会非常危险,因为您最终可能会过度缓存 API 响应。

另外,如果您按文件名进行版本控制 - 例如。 products-1.json / products-2.json 那么你就不需要为max-age过期设置标题了。

【讨论】:

此外,如果您仍然看到缓存不起作用,它可能类似于 Authorization 标头,它可以防止发生缓存。这可能或可能无关紧要,但对于非秘密的静态 .json 文件,它可能不重要 - 您可以删除上面的标题。 我要在这里添加评论,因为这是很好的示例代码。【参考方案4】:

您可以像缓存任何其他页面一样在 Cloudflare 上缓存 JSON 响应 - 通过设置 Cache-Control 标头。因此,如果您想在边缘 (s-maxage) 和浏览器 (max-age) 上缓存 JSON 60 秒,只需在响应中设置以下标头:

Cache-Control: max-age=60, s-maxage=60

您可以在此处阅读有关不同缓存控制标头选项的更多信息:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control

请注意,不同的 Cloudflare 计划允许的最小边缘缓存 TTL 值不同(企业计划允许低至 1 秒)。如果您的标头的值低于此值,那么我想它们可能会被忽略。您可以在此处查看限制:

https://support.cloudflare.com/hc/en-us/articles/218411427-What-does-edge-cache-expire-TTL-mean-#summary-of-page-rules-settings

【讨论】:

以上是关于使用 Cloudflare 缓存 JSON的主要内容,如果未能解决你的问题,请参考以下文章

即使添加 cf 名称服务器,Cloudflare 也不会缓存

Cloudflare更智能的分层缓存拓扑生成

为啥 Cloudflare 不缓存我在 S3 上托管的图像

在启用 CloudFlare 的情况下利用浏览器缓存

PHP网站加速器-Cloudflare风格的完整页面缓存,在1个PHP文件中使用页面规则

使用aws命令行刷新cloudfront缓存