1

EhCache 似乎对用作内存缓存键的对象没有限制,并且仅Serializable用于磁盘/分布式缓存。(http://ehcache.org/apidocs/net/sf/ehcache/Element.html

那么密钥对象的哪个属性在内部用于检查密钥是否与存储的密钥匹配?如果有的话,我可以使用什么方法来提供我自己的身份方法?

4

1 回答 1

1

所以 EHCache 使用equals / hashCode für 密钥标识。

我做了一些测试:

private static final class TestKey implements Serializable {

    boolean equals;
    int hash;

    TestKey( boolean equals, int hash ){
        this.equals = equals;
        this.hash = hash;
    }

    @Override
    public boolean equals( Object other ){ return equals; }

    @Override
    public int hashCode(){ return hash; }
}




public void testIdentity() throws Exception {

    // A simple wrapper around EHCache which does the configuration
    // and provides a map like interface
    CacheEHCache<TestKey,String> cache = CacheEHCache.instance(
            new File( "/tmp/ehcache" ), "testcache", 10 );

    // May contain content from last run
    cache.clear();

    // equals and hash matches
    TestKey k11 = new TestKey( true, 1 );

    cache.put( k11, "Test11" );

    assertEquals( cache.size(), 1 );
    assertTrue( cache.containsKey( k11 ) );

    cache.remove( k11 );
    assertEquals( cache.size(), 0 );

    // doesn't equal but hash matches
    TestKey k21 = new TestKey( false, 1 );

    cache.put( k21, "Test21" );
    assertEquals( cache.size(), 1 );
    assertFalse( cache.containsKey( k21 ) );

    // This is interesting: Clear needs to find the objects to clear
    // So we must patch it.
    k21.equals = true; 
    cache.clear();
    assertEquals( cache.size(), 0 );

    // equals but hash missmatches
    TestKey k31 = new TestKey( true, 1 );
    TestKey k32 = new TestKey( true, 2 );
    cache.put( k31, "Test21" );
    assertEquals( cache.size(), 1 );
    assertTrue( cache.containsKey( k31 ) );
    assertFalse( cache.containsKey( k32 ) );
    cache.clear();
}
于 2014-03-27T07:12:47.780 回答