0

現在、アプリケーションにキャッシングを実装するために EhCache のエンタープライズ バージョンを使用しています。ここで説明したように、EhCache の作成を管理するために使用する EhCache クラスで次のコンストラクターを使用して、プログラムで 2 つの異なるキャッシュ インスタンスを作成しています。

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 クラスの 2 つのインスタンスを作成します。

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

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

上記のメソッドをメイン メソッドで 2 回呼び出します。

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

キャッシュ 1 は正常に作成されましたが、キャッシュ 2 は null です。

キャッシュを作成する順序を入れ替えると:

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

キャッシュ 2 は正常に作成されましたが、キャッシュ 1 は null です。

なぜこれが起こるのか理解できません。最初のキャッシュは正常に作成されますが、2 番目のキャッシュは常に null です。

4

1 に答える 1

1

あなたの問題は、 CacheManager がシングルトンであるため、 CacheManager.create() を2回呼び出すことだと思います。両方のキャッシュを Configuration オブジェクトに追加した後、一度呼び出してみてください。

于 2012-11-28T10:30:03.627 に答える