我有一个springboot应用程序,为此我在方法上应用了缓存来缓存我的结果集。 在Scheduler和初始调用clearCache方法的情况下,此方法可以很好地工作,但是即使在先前调用中清除了缓存之后,也无法再次命中数据库。
@GetMapping(value = "/getCustomers" , produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Customers> getCustomers(HttpServletRequest request,
@RequestParam(name = "clearCache", required = false) boolean clearCache) {
logger.info("Entered getCustomers() clearCache {}", clearCache);
ResponseEntity response = new ResponseEntity(new ErrorResponse("Exception while retrieving customers data"),
new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
try{
List<CustomersInfo> customers = custService.getCustomers(clearCache);
response = getCustomersResponse(customers);
}catch (Exception e) {
logger.error("Exception in getCustomers()"+ e);
}
return response;
}
@Autowired
private CacheService cacheService;
@Cacheable("customers")
public List<CusteomrsInfo> getCustomers(boolean clearCache) {
logger.info("Entered getCustomers() cacheClear {} ", clearCache);
List<LocationInfo> localCompanies = new ArrayList<>();
if (clearCache) {
logger.info("............... requested to clear the cache...............");
cacheService.evictCache();
}
getAllCustomers();
}
@Service
public class CacheService {
private static final Logger logger = LoggerFactory.getLogger(MyService.class);
@Autowired
CacheManager cacheManager;
public void evictCache() {
logger.info("Clearing cache...............");
cacheManager.getCache("customers").clear();
}
@Scheduled(fixedRate = 240000)
public void evictCacheAtIntervals() {
evictCache();
}
我拥有自动和按需清除缓存机制。
当我调用以下端点时,它最初有效(命中数据库) http:// localhost:8265 / myApp / customers / customersInfo?clearCache = true
但稍后致电 http:// localhost:8265 / myApp / customers / customersInfo 不会访问数据库,即使从上一个clearCache调用中清除了数据,它仍然会从缓存中获取数据。
请指导我,谢谢!
答案 0 :(得分:1)
尝试在getCustomers()方法之后添加“ if(clearCache)”。
我的意思是在您使用当前会话之后。
答案 1 :(得分:0)
我解决了这个问题,问题是evictCache()放在了@Cacheable方法下。 我将其放置在调用custService.getCustomers()
之前