@PostConstruct与@Cacheable组合使用缓存失效

背景:

希望在springboot启动时加载一些数据到ECache缓存中,

@PostConstruct
@Cacheable(cacheNames = "cloudResourceVmTypeCache",key = "#root.methodName")
public List<Flavor> flavors(CloudCredential cloudCredential) {
    //TODO something
    return ""

}

测试后发现启动时运行过@PostConstruct方法但缓存并未生效

原因:

        1、@PostConstruct阶段无法保证代理拦截器已经完全启动,对@Cacheable注解起不到拦截作用。

解决方案:

        1、自定义一个监听事件监听ContextRefreshedEvent 或者 ApplicationReadyEvent

@Component
public class MyInitializer implements ApplicationListener<ApplicationReadyEvent> {
    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        //调用@Cacheable方法
    }
}

参考:

https://stackoverflow.com/questions/28350082/spring-cache-using-cacheable-during-postconstruct-does-not-work

https://stackoverflow.com/questions/28350082/spring-cache-using-cacheable-during-postconstruct-does-not-work

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值