我正在使用 Spring Cache @CacheEvict
和 @Cacheable
目前,我每小时运行一个调度程序来清除缓存,下次调用 fetchUser() 时,它将从外部 APi 获取数据并添加到缓存中。
@Scheduled(cron = "0 0 * * * *}")
@CacheEvict(value = "some-unique-value", allEntries = true)
public void clearUserCache() {
log.info("Cache cleared");
}
@Cacheable(value = "some-unique-value", unless = "#result.isFailure()")
@Override
public Result<UserResponse> fetchUser() {
try {
UserResponse userResponse = api.fetchUserDetail();
return Result.success(userResponse);
} catch (Exception e) {
return Result.failure(INTERNAL_SERVER_ERROR);
}
}
现在我们需要的是仅当用户 API 调用成功时才清除缓存。有没有办法做到这一点。
现在缓存已按计划清除,并且假设外部 API 调用失败。主API将返回错误响应。在这种情况下,我应该能够使用现有的缓存本身。
最佳答案
如果我得到的结果是正确的,那么在检查该方法的父方法的 API 调用是否正确后,为什么不将其作为普通方法调用呢?
使用您的代码,类似于
// we just leave scheduled here as you need it.
@Scheduled(cron = "0 0 * * * *}")
@CacheEvict(value = "some-unique-value", allEntries = true)
public void clearUserCache() {
log.info("Cache cleared");
}
@Cacheable(value = "some-unique-value", unless = "#result.isFailure()")
@Override
public Result<UserResponse> fetchUser() {
try {
UserResponse userResponse = api.fetchUserDetail();
return Result.success(userResponse);
} catch (Exception e) {
return Result.failure(INTERNAL_SERVER_ERROR);
}
}
public void parentMethod() {
Result<UserResponse> userResult = this.fetchUser();
if(userResult.isFailure()) {
this.clearUserCache();
}
}
这样,如果抛出任何异常
,它将返回一个失败
状态,您可以检查它。因此,缓存将每小时或当它不起作用时被清除。
所以下次,由于失败并且没有缓存,它会重试。
关于Spring Cache - 仅当 API 响应成功时才清除缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63775298/