将EhCache磁盘库内容加载到内存中

Mat*_*oli 8 java caching ehcache memorycache

EhCache文档中所述:

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

我想内存缓存启动将其所有元素都存储在内存中,我该如何实现呢?

原因是我们的网站对缓存执行了大量访问,因此我们第一次访问网站时响应时间非常短.

Cha*_*dra 5

我假设所有缓存的元素都在 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);
        }
Run Code Online (Sandbox Code Playgroud)

上面的方法从 DiskCache 读取元素,将其删除并放回原处,以便它保留在内存中并删除磁盘版本。

实现 BootstrapCacheLoaderFactory 以便

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

    return loader;
}
.
.
}
Run Code Online (Sandbox Code Playgroud)

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

<cache
         name="DummyCacheEl"
         maxElementsInMemory="3500"
         eternal="true"
         overflowToDisk="false"
         diskPersistent="true"
         memoryStoreEvictionPolicy="LRU">
         <bootstrapCacheLoaderFactory class="CustomBootstrapCacheLoaderFactory"  properties="async=true"/>
</cache>  
Run Code Online (Sandbox Code Playgroud)

  • +1 BootstrapCacheLoader。关于从磁盘中删除并将它们加载到内存中的代码中的一个小建议,Element el = cache.removeAndReturnElement(key); 我会推荐这种方法,而不是先获取然后删除元素。 (2认同)