java - 在 Spring MVC 应用程序中缓存 HTTP 响应

标签 java spring caching spring-mvc

我希望我的 Spring Controller 缓存返回的内容。我发现了很多关于如何禁用缓存的问题。我想知道如何启用缓存。我的 Controller 看起来像这样:

@Controller
public class SimpleController {

    @RequestMapping("/webpage.htm")
    public ModelAndView webpage(HttpServletRequest request, 
                                HttpServletResponse response) {
        ModelAndView mav = new ModelAndView("webpage");
        httpServletResponse.setHeader(“Cache-Control”, “public”);
        //some code
        return mav;
    }
}

如您所见,我添加了以下行:httpServletResponse.setHeader(“Cache-Control”, “public”); 来设置缓存,但是在我的浏览器中,当我刷新此页面时,我仍然获得相同的状态结果:200 OK。如何实现 304 not modified 结果?我可以在此方法上设置注释 @ResponseStatus(value = HttpStatus.NOT_MODIFIED) 但它只是状态还是实际缓存?

最佳答案

引用 14.9.1 What is Cacheable :

public - Indicates that the response MAY be cached by any cache, even if it would normally be non-cacheable or cacheable only within a non- shared cache.

基本上 Cache-Control: public 是不够的,它只要求浏览器缓存正常不缓存的资源,例如通过 HTTPS。

HTTP 中的缓存实际上相当复杂,它涉及到其他几个 header :

  • Cache-Control - 上面讨论过

  • Expires - 当给定资源应被视为过时

  • Last-Modified - 上次修改资源的时间

  • ETag - 资源的唯一标签,在每次修订中都会更改

  • Vary - 根据不同的header单独缓存

  • If-Modified-Since, If-None-Match, ...

我找到了 Caching Tutorial相当全面。并非所有 header 都应该一起使用,您必须真正确定自己在做什么。因此,我建议使用内置解决方案,如 EhCache web caching .

同样,用如此低级的细节污染你的 Controller 也不是一个好主意。

关于java - 在 Spring MVC 应用程序中缓存 HTTP 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12997517/

相关文章:

Java:在网页加载到网络浏览器之前编辑网页

java - GIJ(Java 的 GNU 解释器)是否足够稳定以用于商业用途?

java - 在应用程序启动时缓存数据库表数据

java - 缓存部分 2D 绘图是一种好习惯吗?

java - fatal error : SIGSEGV everytime I launch Android studio

java - 从 mysql 查询返回时出现空指针异常

java - Spring MVC 3.2.8 : Create a new FileSystemXmlApplicationContext and loading the definitions from the given XML files

java - 为什么我的项目找不到 org.springframework.test 或 org.springframework.boot.test?

java - 关于应用程序级上下文缓存的设计思路(类似于Web中的 session /应用程序上下文)

php - 跨多个服务器使用 Zend Cache 和 AWS ElastiCache 的缓存值不一致