gpt4 book ai didi

spring-boot - @Cacheable 在 Controller 中工作,但不在服务内部

转载 作者:IT王子 更新时间:2023-10-29 06:08:51 26 4
gpt4 key购买 nike

我在 Spring Boot 中遇到了这个奇怪的问题,其中 @Cacheable 在 Controller 中工作但不在服务内部。我可以在 Redis 中看到 GET 调用,但看不到 PUT 调用。

这是有效的,因为它在 Controller 内部

@RestController
@RequestMapping(value="/places")
public class PlacesController {

private AwesomeService awesomeService;

@Autowired
public PlacesController(AwesomeService awesomeService) {
this.awesomeService = awesomeService;
}

@GetMapping(value = "/search")
@Cacheable(value = "com.example.webservice.controller.PlacesController", key = "#query", unless = "#result != null")
public Result search(@RequestParam(value = "query") String query) {
return this.awesomeService.queryAutoComplete(query);
}
}

但是当我在服务中这样做时,@Cacheable 不工作

@Service
public class AwesomeApi {

private final RestTemplate restTemplate = new RestTemplate();

@Cacheable(value = "com.example.webservice.api.AwesomeApi", key = "#query", unless = "#result != null")
public ApiResult queryAutoComplete(String query) {
try {
return restTemplate.getForObject(query, ApiResult.class);
} catch (Throwable e) {
return null;
}
}
}

我可以在 Redis 中看到 GET 调用,但看不到 PUT 调用。

最佳答案

您的缓存应该可以正常工作。确保您有 @EnableCaching 注释并且您的 unless 条件是正确的。

现在,您正在使用 unless="#result != null",这意味着它将缓存结果,除非它不是 null。这意味着它几乎永远不会缓存,除非 restTemplate.getForObject() 返回 null,或者发生异常时,因为那时您也将返回 null

我假设您想缓存每个值,null 除外,但在那种情况下您必须反转您的条件,例如:

@Cacheable(
value = "com.example.webservice.api.AwesomeApi",
key = "#query",
unless = "#result == null") // Change '!=' into '=='

或者,as mentioned in the comments ,而不是反转条件,您可以使用 condition 代替 unless:

@Cacheable(
value = "com.example.webservice.api.AwesomeApi",
key = "#query",
condition = "#result != null") // Change 'unless' into 'condition'

关于spring-boot - @Cacheable 在 Controller 中工作,但不在服务内部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51373323/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com