Java ehCache,如何替换成员

时间:2018-02-23 10:13:23

标签: java ehcache

我有一个简单的方法,我已经注释了缓存。

  @Cacheable(value = "devices", key = "#hardwareId", unless = "#result == null")
  public Device get(String hardwareId)

我有一种机制可以知道有人更改底层数据库的时间。所以我知道从缓存中驱逐一个成员,以便下次调用将返回到数据库。

 getCache().remove(hardwareId);

我想做什么更新缓存中的元素。这样做的原因是回调数据库可能需要1000ms&我不想对方法的表现有所了解。

据我所知,我有两种选择。

选项1:

当我驱逐该成员时,请在此时回复该服务。

 getCache().remove(hardwareId);
 service.get(hardwareId);

选项2:

  • 创建'net.sf.ehcache.bootstrap.BootstrapCacheLoader'的实例 在启动时注册要通知元素的同一个类 从缓存中删除(notifyElementRemoved())。
  • 在@PostContruct上获取所有使用@Cacheable注释的方法。创建一个地图 'cacheName'到Method实例(java反射方法)
  • 当触发notifyElementRemoved()时,使用缓存名称获取Method实例,并调用它以触发重新填充的缓存。

    Method method = map.get(cacheName);
    // Add magic here to get the service.
    Object serviceInstance = applicationContext.getBean("deviceService");
    
    if (Proxy.isProxyClass(serviceInstance.getClass())) {
      Proxy.getInvocationHandler(serviceInstance).invoke(serviceInstance, method, new Object[] {objectKey});
    } else {
      method.invoke(serviceInstance, objectKey);
    }
    

选项1的缺点是我必须修改30多个类才能输入逻辑来回调服务。

选项2的缺点是它有点复杂,感觉ehCache可以提供此功能会很好。它知道它包装了什么方法,它知道调用此方法的键/参数是什么。

这两个选项的缺点是总是有一段时间缓存不包含成员&可能会导致表现不佳。

我的问题是,ehCache是​​否提供了我想要的功能,还是有另外一种机制可以在缓存中零成员空闲时更新缓存中的成员?

0 个答案:

没有答案