SpringBoot - 在 Rest 方法中添加缓存控制头

我有一个基本的 SpringBoot 2.0.5.RELEASE 应用程序。使用 Spring Initializer、JPA、嵌入式 Tomcat、Thymeleaf 模板引擎,并打包为可执行 JAR


我创建了这个 Rest 方法:


  @GetMapping(path = "/users/notifications", consumes = "application/json", produces = "application/json")

    public ResponseEntity<List<UserNotification>> userNotifications(

            @RequestHeader(value = "Authorization") String authHeader) {


        User user = authUserOnPath("/users/notifications", authHeader);


        List<UserNotification> menuAlertNotifications = menuService

                .getLast365DaysNotificationsByUser(user);


        return ResponseEntity.ok(menuAlertNotifications)

                .cacheControl(CacheControl.maxAge(60, TimeUnit.SECONDS));;


    }

我想添加一个缓存控制标头,但我不知道如何...我收到一个编译错误:


Multiple markers at this line

    - The method cacheControl(CacheControl) is undefined for the type 

     ResponseEntity<List<UserNotification>>

    - CacheControl

    - cacheControl

我还添加了这个属性 application.properties


security.headers.cache=false


30秒到达战场
浏览 182回答 1
1回答

holdtom

当您使用ResponseEntity.ok(T body)返回类型时,ResponseEntity<T>因为它是一种将数据添加到ResponseEntity.您需要通过ResponseEntity.ok()没有返回Builder对象的参数创建的构建器对象。然后,您可以通过 body 方法自己添加数据。所以你的代码应该是这样的&nbsp; @GetMapping(path = "/users/notifications", consumes = "application/json", produces = "application/json")&nbsp; &nbsp; public ResponseEntity<List<UserNotification>> userNotifications(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @RequestHeader(value = "Authorization") String authHeader) {&nbsp; &nbsp; &nbsp; &nbsp; User user = authUserOnPath("/users/notifications", authHeader);&nbsp; &nbsp; &nbsp; &nbsp; List<UserNotification> menuAlertNotifications = menuService&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .getLast365DaysNotificationsByUser(user);&nbsp; &nbsp; &nbsp; &nbsp; return ResponseEntity.ok().cacheControl(CacheControl.maxAge(60, TimeUnit.SECONDS)).body(menuAlertNotifications);&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java