Java 如何为使用SpringCache缓存的SpringWeb服务设置正确的上次修改的头值?
我有这样的Spring MVC控制器:Java 如何为使用SpringCache缓存的SpringWeb服务设置正确的上次修改的头值?,java,spring,spring-mvc,caching,spring-cache,Java,Spring,Spring Mvc,Caching,Spring Cache,我有这样的Spring MVC控制器: @Controller @RequestMapping(value = "/user") public class UserController { ..... @Cacheable(value = "users", key = "#id") @RequestMapping(value = "/get", method = RequestMethod.GET) @ResponseBody public User g
@Controller
@RequestMapping(value = "/user")
public class UserController {
.....
@Cacheable(value = "users", key = "#id")
@RequestMapping(value = "/get", method = RequestMethod.GET)
@ResponseBody
public User getUser(Long id){
return userService.get(id);
}
....
}
我想将上次修改的头添加到GetUser web服务的HTTP响应中。当缓存添加到我的商店时,我如何获得正确的日期?
如何将上次使用此日期修改的标题添加到Spring控制器方法的响应中?如何:
@Controller
@RequestMapping(value = "/user")
class UserController {
@Cacheable(value = "users", key = "#id")
@RequestMapping(value = "/get", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<User> getUser(Long id) {
HttpHeaders headers = new HttpHeaders();
headers.set("Last-Modified", dateFormat.format(new Date()));
return new ResponseEntity<SecurityProperties.User>(headers, userService.get(id), HttpStatus.OK);
}
}
@控制器
@请求映射(value=“/user”)
类用户控制器{
@可缓存(value=“users”,key=“#id”)
@RequestMapping(value=“/get”,method=RequestMethod.get)
@应答器
公共响应权限getUser(长id){
HttpHeaders=新的HttpHeaders();
headers.set(“上次修改”,dateFormat.format(new Date());
返回新的ResponseEntity(headers,userService.get(id),HttpStatus.OK);
}
}
Spring已经内置了一个支持,用于处理驱动请求处理程序方法中上次修改的和(如果自
修改)头
它是基于
此示例取自java文档:
这还将透明地为修改的案例和未修改的案例设置适当的响应头。典型用法:
但是您的@Cacheable
注释是一个问题,因为它阻止执行方法(第二次调用),因此不会调用请求。checkNotModified
。-如果缓存很重要,那么您可以从控制器方法中删除@Cacheable
注释,并将其放在一个内部方法上,该方法在请求后调用。checkNotModified
完成
此实现违背了上次修改的重新验证的目的。如果数据发生更改,过时的数据仍将使用上次修改的旧日期从缓存中提供。如果将@Cacheable
添加到@RequestMapping
中,则不会达到此目的?@dschulten:它适用于基于注释的控制器-我正在使用它!
@RequestMapping(value = "/get", method = RequestMethod.GET)
public String myHandleMethod(WebRequest webRequest, Model model) {
long lastModified = // application-specific calculation
if (request.checkNotModified(lastModified)) {
// shortcut exit - no further processing necessary
return null;
}
// further request processing, actually building content
model.addAttribute(...);
return "myViewName";
}
//use selfe in order to use annotation driven advices
@Autowire
YourController selfe;
@RequestMapping(value = "/get", method = RequestMethod.GET)
public String myHandleMethod(WebRequest webRequest, Model model) {
long lastModified = // application-specific calculation
if (request.checkNotModified(lastModified)) {
// shortcut exit - no further processing necessary
return null;
} else {
return selfe.innerMyHandleMethod(model);
}
}
@Cacheable(value = "users", key = "#id")
public String innerMyHandleMethod(Model model) {
model.addAttribute(...);
return "myViewName";
}