使用Cloudflare缓存JSON

eca*_*buk 7 cloudflare

我正在为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
Run Code Online (Sandbox Code Playgroud)

CloudFlare缓存我服务器的响应以降低成本吗?因为我不会使用CSS,图像等

ech*_*ish 17

标准Cloudflare缓存级别(在您的域的性能设置下)设置为标准/积极,这意味着它仅通过默认脚本,样式表,图像缓存某些类型.积极的缓存不会缓存正常的网页(即在目录位置或*.html),也不会缓存JSON.所有这些都基于URL模式(例如,它以.jpg结尾吗?)而不管Content-Type标头.

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

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

顺便说一下,我不建议使用HTML Content-Type进行JSON响应.


mih*_*sen 6

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

https:/domain.com/sub-directiory/*.json*
Run Code Online (Sandbox Code Playgroud)

  • 缓存级别:缓存一切
  • 浏览器缓存 TTL:设置超时
  • 边缘缓存 TTL:设置超时

json 的 Cloudflare 页面规则

希望它可以挽救某人的一天。


Sim*_*ver 5

新的工人功能(额外 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;
  }
}
Run Code Online (Sandbox Code Playgroud)

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

此外,如果您按文件名进行版本控制 - 例如。products-1.json/products-2.json然后你不需要设置max-age过期的标头。