user3919727
user3919727

Reputation: 343

Springboot cache not working on subsequent on demand clear cache calls

I have a springboot application for which I applied cache on a method to cache my result sets. This works fine with Scheduler and initial calls to clearCache method but fails to hit the db again even after cache clear in the previous calls.

@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();
     }

I have both automatically as well as on demand clear cache mechanism.

It works initially (hits the db) when I call the below endpoint http://localhost:8265/myApp/customers/customersInfo?clearCache=true

But later calls on http://localhost:8265/myApp/customers/customersInfo does not hit the db, it still gets the data from the cache even though its been cleared in the previous clearCache call.

Please guide me, thanks in advance

Upvotes: 0

Views: 362

Answers (2)

user3919727
user3919727

Reputation: 343

I resolved this, the issue was evictCache() was placed under the method with @Cacheable. I placed this before invoking custService.getCustomers()

Upvotes: 0

Raj  Kommawar
Raj Kommawar

Reputation: 335

Try adding "if (clearCache) " after getCustomers() methods.

I mean after your use of current session.

Upvotes: 1

Related Questions