微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

SpringBoot缓存在后续的按需清除缓存调用中不起作用

如何解决SpringBoot缓存在后续的按需清除缓存调用中不起作用

我有一个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调用中清除了数据,它仍然会从缓存中获取数据。

请指导我,谢谢!

解决方法

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

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

,

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

之前

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。