gpt4 book ai didi

java - 我是否应该手动返回 ReSTLet 中缓存请求 (ETag) 的 304 响应?

转载 作者:行者123 更新时间:2023-11-30 02:44:48 26 4
gpt4 key购买 nike

我向我的应用程序添加了自定义缓存行为,类似于 Thierry 提出的 in this article 。对于静态内容中的每个 CSS、JS 和 HTML 文件服务器,我添加以下两个 header :

// Added by me
ETag: "0c635aa7113262fac7606da2432e00f5" // md5(last_mod_date_of_file)
Cache-Control: max-age=31536000 // one year

// Automatically added by Restlet (probably Directory class?)
Date: Wed, 09 Nov 2016 11:50:53 GMT
Expires: Wed, 09 Nov 2016 12:00:53 GMT
Last-Modified: Wed, 09 Nov 2016 17:30:56 GMT

这工作正常,但我注意到在测试服务器上部署代码并在 Chrome 中点击 F5 后,我再次获取整个响应正文(返回 HTTP 200)。

我注意到这些请求也使用了正确的 header :

Cache-Control:max-age=0
If-Modified-Since: Wed, 09 Nov 2016 17:30:56 GMT
If-None-Match: "0c635aa7113262fac7606da2432e00f5"

我的问题是,我是否应该在服务器过滤器中对 If-None-Match header 进行手动验证并返回 304 响应?或者是由 ReSTLet 处理的?

注意:这个问题有点奇怪的是它似乎在我的本地开发环境中正常工作。我也有点困惑为什么 ReSTLet 将 Expires 设置为 之前 Last-Modified 的日期。我将尝试调试这是否是万恶之源,但这并不会使我关于手动设置 304 状态和检查服务器上的 ETag 的问题无效。

最佳答案

好的,我已经弄清楚了这个问题,并在下面发布了答案。

我是否应该在服务器过滤器中对 If-None-Match header 进行手动验证并返回 304 响应?

不,您不必自己手动执行此操作。这由 ReSTLet 自动处理( DirectoryServerResource 负责处理)。

那么问题是什么?

问题确实出在 Last-Modified标题被设置为 future 的日期。发生这种情况是因为我的生产服务器位于 UTC-8时区,而我正在开发 UTC+1 .

我是如何解决这个问题的?

这需要熟悉 ReSTLet API,但当时的解决方案很简单。我确保当我的应用程序启动时,它会显示 File Last Modified操作系统中我的应用程序目录的属性,因为这是我想在 Last-Modified 中使用的值 header 。现在,您不能只在 response 上设置此 header 在 Filter ,因为 HTTP 缓存 header 的自动处理发生在提到的 DirectoryServerResource 之前。类(class)。所以解决办法如下:

创建一个扩展 DSR 的类(免费为您提供所有自动缓存处理)并修改其 handle()方法使得 Last-Modified在此逻辑启动之前设置 header :

 public class WebAssetsResource extends DirectoryServerResource {
@Override
public Representation handle() {
Date desiredDate = ...; // I read this from File System
getInfo().setModificationDate(desiredDate);
return super.handle(); // Automatic logic will use desired date
}
}

现在,请确保自定义 Directory 使用您新创建的资源类。

public class CachedWebAssetsDirectory extends Directory {
public CachedWebAssetsDirectory(Context context, Reference rootLocalReference) {
super(context, rootLocalReference);
setTargetClass(WebAssetsResource.class); // Needed so that Restlet will use our implementation of a ServerResource to serve static files
}
}

之后您可以使用CachedWebAssetsDirectory如您所愿,在此基础上构建任何自定义过滤器。

关于java - 我是否应该手动返回 ReSTLet 中缓存请求 (ETag) 的 304 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40507063/

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