2012-11-28 28 views
0

我目前在我們的應用程序中使用企業版的EhCache來實現緩存。作爲解釋here,我用下面的構造,我的Ehcache類,我用它來管理的Ehcache創建創建兩個不同的緩存實例編程:NullPointerException在Terracotta集羣上創建兩個不同的緩存時

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中創建成功但cache2爲空。

如果我立交,我創建了緩存的順序:

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

緩存2成功創建,但cache1的爲空。

我無法理解爲什麼會發生這種情況。第一個緩存創建成功,但第二個緩存始終爲空。

回答

1

我認爲你的問題是你調用CacheManager.create()兩次,因爲CacheManager是一個Singleton。嘗試在將兩個緩存添加到配置對象後調用一次。

相關問題