【问题标题】:Load EhCache diskstore content into memory将 EhCache 磁盘存储内容加载到内存中
【发布时间】:2012-05-13 23:10:05
【问题描述】:

EhCache documentation中所说:

在实践中,这意味着持久性内存缓存将在磁盘上启动其所有元素。 [...] 因此,Ehcache 设计不会在启动时将它们全部加载到内存中,而是根据需要延迟加载它们。

我希望内存缓存启动时所有元素都在内存中,我该如何实现?

原因是我们的网站对缓存执行了很多的访问,所以我们第一次访问该网站时响应时间很差。

【问题讨论】:

  • 你能在启动时遍历所有条目吗?
  • 这就是我目前所做的,但它的完成方式非常慢(我在循环中调用高级方法,这些高级方法也会发出数据库请求)。如果有一种方法可以直接使用 EhCache API 简单地迭代所有条目,那可能会很好。

标签: java caching ehcache memorycache


【解决方案1】:

我假设所有缓存的元素都在 DiskStore 中,并且您希望它们在应用程序启动后立即在内存中。无论如何使用 BootStrapCacheLoader 和 BootstrapCacheLoaderFactory 应该会有所帮助。

我只是想知道我们在应用程序启动后将 DiskStore 加载到内存中的位置

您可以实现 BootstrapCacheLoader,它将加载缓存元素,如下所示。 BootstrapCacheLoader.load(Ehcache cache)方法的定义可以是

       //CustomBootstrapCacheLoader implements BootstrapCacheLoader


        List<?> keys = cache.getKeys();

        if ((keys == null) || keys.isEmpty())
        {
            return;
        }

        for (Object key : keys)
        {
           Element el = cache.getQuiet(key);
           cache.removeQuiet(key);
           cache.putQuiet(el);
        }

上述方法从 DiskCache 中读取元素,将其移除并放回原处,使其留在内存中,并移除磁盘版本。

实现 BootstrapCacheLoaderFactory 以便

public class CustomBootstrapCacheLoaderFactory extends BootstrapCacheLoaderFactor
{
.
.
@Override
public BootstrapCacheLoader createBootstrapCacheLoader(Properties properties)
{
    CustomBootstrapCacheLoader loader = new CustomBootstrapCacheLoader();
    loader.setAsynchronous(getAsyncFromProperty(properties));

    return loader;
}
.
.
}

您可以使用 CustomBootstrapCacheLoaderFactory 如下定义缓存配置

<cache
         name="DummyCacheEl"
         maxElementsInMemory="3500"
         eternal="true"
         overflowToDisk="false"
         diskPersistent="true"
         memoryStoreEvictionPolicy="LRU">
         <bootstrapCacheLoaderFactory class="CustomBootstrapCacheLoaderFactory"  properties="async=true"/>
</cache>  

【讨论】:

  • +1 用于 BootstrapCacheLoader。代码中关于从磁盘中删除并将它们加载到内存中的一个小建议,Element el = cache.removeAndReturnElement(key);我会推荐这种方法,而不是先获取然后删除元素。
  • True,但它会通知 CacheEventListener 。引导缓存时可能不需要。
  • 是的,所以如果没有为该缓存配置通知程序,那么这将有助于提高性能。
  • 是的。此外,我们必须异步加载缓存(在 loadcache 方法中生成一个线程),以便它现在阻塞实例启动
  • removes it and Puts it back so that it stays in the memory and disk version is removed. 我不想从磁盘缓存中删除元素?我只想将它们加载到内存中。
猜你喜欢
  • 1970-01-01
  • 2012-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-03
  • 2010-12-29
  • 2019-07-22
相关资源
最近更新 更多