有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么在Spring MVC中对http缓存控制的支持较差?

阅读REST practice一书,更好地理解基于缓存的web横向扩展。但当我试图在Spring Boot项目中添加http缓存控制时,我发现缓存控制没有什么特别之处。我得到的唯一资源是ResponseEntity:javadoc。ETag最有用的文章是http://www.baeldung.com/etags-for-rest-with-spring

这让我很困惑。。。如果缓存控制真的很好,为什么几乎找不到对Etag生成和缓存控制资源的支持?或者这不是目前最好的做法

现在,我的实现如下所示:

@RestController
public class Api {

    @GetMapping("/with-cache")
    public ResponseEntity cache() throws InterruptedException {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setCacheControl("max-age=3600");
        httpHeaders.setETag("\"3Rstthw\"");
        Thread.sleep(1000);
        return new ResponseEntity<>("Hello", httpHeaders, HttpStatus.OK);
    }
}

看起来不太优雅。希望有人能给出答案


共 (1) 个答案

  1. # 1 楼答案

    注释were considered for response headers但决定不使用,因此您必须以某种方式手动处理它(但不一定像代码中那样)

    做出反对决定的主要原因是,响应很复杂,可能存在重定向等问题,因此注释不太合适

    引用上一条评论

    The specific use case brought up here is Cache-Control. Note that in 4.1 we added ResponseEntity builders and in 4.2 we added a CacheControl builder that works with the ResponseEntity builders making it very convenient to do that programmatically and has some further benefits when combined with eTags and lastModified (an automatic check + 304). We also specifically considered and decided against a @CacheControl header since this a cross-cutting requirement. Instead the WebContentInterceptor can be used to configure cache settings per URL pattern and that accepts a CacheControl builder as well.