gpt4 book ai didi

ios - NSURLCache 缓存不应缓存的随机响应

转载 作者:可可西里 更新时间:2023-11-01 03:30:06 25 4
gpt4 key购买 nike

我正在实现一个应用程序,它对我们也控制的 rest-api 进行大量网络调用。最近我们决定在服务器端引入缓存 header 以节省一些宝贵的网络和服务器时间。由于我们事先不知道数据的有效期,我们没有发送 Cache-control: max-ageExpires header ,我们所做的只是发送一个Last-Modified header 与 E-tag 一起使用,因此我们总是会访问服务器,但大多数时候响应都非常快,304 .一开始一切似乎都很好,许多请求都被缓存了。但是,由于缓存,我在应用程序上遇到了一些随机数据错误

出于某种原因,我无法理解,在某些时候,请求被本地缓存并用作“更新”数据而无需访问服务器,而实际上并非如此。问题一直存在,直到一段时间过去。然后所有内容再次正常发送到服务器,就像使用 cache-control header 一样,但没有它!。所以,我的问题是:


NSURLCacheNSURLConnection 如何决定一个特定的请求不需要上线,当原始请求没有带有 Cache-control: max -ageExpires header ?有没有人经历过类似的影响?以及如何在不删除整个缓存的情况下解决它?


更多背景信息:

  • 我正在使用 AFNetworking , 但它依赖于 NSURLConnection 所以我不认为它改变了一切
  • 使用的缓存是默认的[NSURLCache sharedURLCache]实例
  • 这是一个 GET 请求,当我从缓存的响应中检查 header 时,这是我得到的:

    po [响应所有HeaderFields]

    "Access-Control-Allow-Headers" = "Content-Type";
    "Access-Control-Allow-Methods" = "GET, POST, DELETE, PUT";
    "Access-Control-Allow-Origin" = "*";
    Connection = "keep-alive";
    "Content-Encoding" = gzip;
    "Content-Length" = 522;
    "Content-Type" = "application/json";
    Date = "Mon, 02 Sep 2013 08:00:38 GMT";
    Etag = "\"044ad6e73ccd45b37adbe1b766e6cd50c\"";
    "Last-Modified" = "Sat, 31 Aug 2013 10:36:06 GMT";
    Server = "nginx/1.2.1";
    "Set-Cookie" = "JSESSIONID=893A59B6FEFA51566023C14E3B50EE1E; Path=/rest-api/; HttpOnly";
  • 我无法预测或重现错误何时会发生,因此依赖于删除缓存的解决方案不是一种选择。

  • 我正在使用 iOS5+

最佳答案

How can NSURLCache together with NSURLConnection decide that a particular request does not need to go online when...

RFC 2616 的第 13.2 节说:

Since origin servers do not always provide explicit expiration times, HTTP caches typically assign heuristic expiration times, employing algorithms that use other header values (such as the Last-Modified time) to estimate a plausible expiration time. The HTTP/1.1 specification does not provide specific algorithms, but does impose worst-case constraints on their results. Since heuristic expiration times might compromise semantic transparency, they ought to used cautiously, and we encourage origin servers to provide explicit expiration times as much as possible.

因此,即使您没有为数据提供特定的生命周期,URL 加载系统也有可能确定缓存的数据“足够新鲜”。

为了获得最佳结果,您应该尝试在响应 header 中提供特定的生命周期。如果不可能添加这样的 header ,也许您可​​以改为更改请求。 if-modified-sincecache-control 都可以帮助您避免缓存数据。

关于ios - NSURLCache 缓存不应缓存的随机响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18570105/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com