java - 在 Terracotta 集群上创建两个不同的缓存时出现 NullPointerException

标签 java nullpointerexception ehcache

我目前正在使用企业版 EhCache 在我们的应用程序中实现缓存。正如所解释的here ,我通过在我的 EhCache 类中使用以下构造函数以编程方式创建两个不同的缓存实例,我用它来管理 EhCache 创建:

public class EhCache implements ICacheAccess {    

    private String name;
    private Cache ehCache;
    private CacheAttributes attrs;

    public EhCache(final String name, final CacheAttributes attrs) {
                this.name = name;
                this.attrs = attrs;

                Configuration configuration = new Configuration();


                TerracottaClientConfiguration terracottaConfig 
                    = new TerracottaClientConfiguration();

                configuration.addTerracottaConfig(terracottaConfig);

                final CacheConfiguration cfg = new CacheConfiguration(name, attrs.cacheSize)          
                    .eternal(attrs.eternal).terracotta(new TerracottaConfiguration())
                    .timeToLiveSeconds(attrs.timeToLiveSeconds)
                    .timeToIdleSeconds(attrs.timeToIdleSeconds)
                    .statistics(attrs.statistics).overflowToOffHeap(true).maxBytesLocalOffHeap(200,MemoryUnit.MEGABYTES);

                configuration.addCache(cfg);    


                CacheConfiguration defaultCache = new CacheConfiguration("default",
                        1000).eternal(false);
                configuration.addDefaultCache(defaultCache);

                CacheManager mgr = CacheManager.create(configuration);        
                ehCache = mgr.getCache(name);        
                LOGGER.log("ehcache is "+ehCache);           
            } 
}

然后,我使用以下方法创建 EhCache 类的两个实例:

public void testCreateCache(String name) {
        CacheAttributes attrs = new CacheAttributes();        
                attrs.timeToIdleSeconds = 0;
                attrs.timeToLiveSeconds = 0;

        Cache cache = new EhCache(name, attrs);
    }

我在主方法中调用上述方法两次:

testCreateCache("cache1");
testCreateCache("cache2");

缓存1创建成功,但缓存2为空。

如果我交换创建缓存的顺序:

 testCreateCache("cache2");
 testCreateCache("cache1");

缓存2创建成功,但缓存1为空。

我无法理解为什么会发生这种情况。第一个缓存创建成功,但第二个缓存始终为空。

最佳答案

我认为你的问题是你调用了 CacheManager.create() 两次,因为 CacheManager 是单例。将两个缓存添加到配置对象后尝试调用它一次。

关于java - 在 Terracotta 集群上创建两个不同的缓存时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13600626/

相关文章:

android - 将字符串数组传递给另一个 Activity

java - 集群 ehcache 的 Junit 测试策略

java - 缓存大量有序集合

java - Oracle 查询根据子表中的值对表进行过滤和排序

java - 将 Web 应用程序本地部署到客户端

java - 在 LibGDX、Java 中使用 AssetManager 加载资源

java - 什么是NullPointerException,我该如何解决?

java - 在两个字段上创建 Hibernate 标准以及类似查询

java中的java.lang.NullPointerexception

java - 即使在 timeToLiveSeconds 和/或 timeToIdleSeconds 之后,Ehcache 也不会从缓存中删除元素