【发布时间】:2020-05-03 06:28:17
【问题描述】:
我在 Springboot 中开发了一个 REST 端点,它采用 String ID 并以 ModelAndView 响应。此端点标有@Cacheable 注释。现在在给定的端点上可能会发生两件事。
案例 1:请求 ID 存在于数据库中,并产生一个需要重定向到的 URL。在这种情况下,响应应该被缓存,以便在相同 ID 的连续请求时,可以从缓存中提供结果
案例 2:请求的 ID 在数据库中不存在,因此重定向应该发生在特定的 URL 上,并且在这种情况下不应该进行缓存。
下面是我的方法
@GetMapping("{id}")
@Cacheable(value = "url-single", key = "#id", unless = "#result.view!=\"redirect:/notfound\"")
public ModelAndView redirect(@PathVariable("id") String id, ServletRequest servletRequest,
ServletResponse servletResponse) {
HttpServletRequest request = HttpServletRequest.class.cast(servletRequest);
LOG.info("Redirection request from: {} for Short URL Key: {}", request.getRemoteAddr(), id);
try {
Optional<String> originalUrlOptional = urlManagerService.retrieveOriginalUrl(id);
if (originalUrlOptional.isPresent() && !StringUtils.isEmpty(originalUrlOptional.get())) {
LOG.info("Found Original URL: {} for Short URL Key: {}", originalUrlOptional.get(), id);
return new ModelAndView("redirect:https://" + originalUrlOptional.get());
}
} catch (NoSuchElementException e) {
LOG.error("Error while redirecting: {}", e.getMessage(), e);
}
return new ModelAndView("redirect:/notfound");
}
如果我从here 中正确理解,@Cacheable 中的关键字unless 适用于返回类型,并且为了访问返回类型对象的任何特定成员变量,我们必须将其称为#result.attributeName <comparison> <value>。
那么为什么我的 Redis 缓存中没有存储任何内容?如果我删除 unless 条件,所有内容都会被存储。条件不正确吗?
【问题讨论】:
-
你不能将重定向逻辑与缓存分开吗?
标签: java spring-boot caching redis spring-cache