【问题标题】:Springboot cache not working on subsequent on demand clear cache callsSpring Boot 缓存不适用于后续按需清除缓存调用
【发布时间】:2020-08-27 21:49:46
【问题描述】:

我有一个 springboot 应用程序,我在一个方法上应用了缓存来缓存我的结果集。 这适用于调度程序和对 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 调用中被清除了。

请指导我,提前谢谢

【问题讨论】:

    标签: java spring-boot spring-cache


    【解决方案1】:

    尝试在 getCustomers() 方法之后添加“if (clearCache)”。

    我的意思是在您使用当前会话之后。

    【讨论】:

      【解决方案2】:

      我解决了这个问题,问题是 evictCache() 被放在了 @Cacheable 的方法下。 我在调用 custService.getCustomers() 之前放置了这个

      【讨论】:

        猜你喜欢
        • 2019-05-02
        • 1970-01-01
        • 2017-03-29
        • 2021-01-25
        • 2018-11-09
        • 1970-01-01
        • 1970-01-01
        • 2014-07-04
        • 2018-12-16
        相关资源
        最近更新 更多