提交 523a83ca 编写于 作者: C Costin Leau

SPR-8008

SPR-8023
+ fix bug in Ehcache cache that considered expired entries for key checks
上级 d7a8cf4b
......@@ -58,10 +58,14 @@ public class EhCacheCache implements Cache<Object, Object> {
}
public boolean containsKey(Object key) {
return cache.isKeyInCache(key);
// get the element to force the expiry check (since #isKeyInCache does not considers that)
Element element = cache.getQuiet(key);
return (element != null ? true : false);
}
public boolean containsValue(Object value) {
// force expiry check to guarantee a valid result (otherwise expired elements are considered)
cache.evictExpiredElements();
return cache.isValueInCache(value);
}
......@@ -77,11 +81,8 @@ public class EhCacheCache implements Cache<Object, Object> {
}
public Object remove(Object key) {
Object value = null;
if (cache.isKeyInCache(key)) {
Element element = cache.getQuiet(key);
value = (element != null ? element.getObjectValue() : null);
}
Element element = cache.getQuiet(key);
Object value = (element != null ? element.getObjectValue() : null);
cache.remove(key);
return value;
}
......
/*
* Copyright 2010 the original author or authors.
* Copyright 2010-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
......@@ -16,8 +16,11 @@
package org.springframework.cache.ehcache;
import static org.junit.Assert.*;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import org.junit.Test;
import org.springframework.cache.Cache;
import org.springframework.cache.vendor.AbstractNativeCacheTest;
......@@ -41,4 +44,21 @@ public class EhCacheCacheTest extends AbstractNativeCacheTest<Ehcache> {
protected Cache createCache(Ehcache nativeCache) {
return new EhCacheCache(nativeCache);
}
}
@Test
public void testExpiredElements() throws Exception {
String key = "brancusi";
String value = "constantin";
Element brancusi = new Element(key, value);
// ttl = 10s
brancusi.setTimeToLive(3);
nativeCache.put(brancusi);
assertTrue(cache.containsKey(key));
assertEquals(value, cache.get(key));
// wait for the entry to expire
Thread.sleep(5 * 1000);
assertFalse("expired entry returned", cache.containsKey(key));
assertNull(cache.get(key));
}
}
\ No newline at end of file
......@@ -16,9 +16,7 @@
package org.springframework.cache.vendor;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
......@@ -31,8 +29,8 @@ import org.springframework.cache.Cache;
*/
public abstract class AbstractNativeCacheTest<T> {
private T nativeCache;
private Cache cache;
protected T nativeCache;
protected Cache cache;
protected final static String CACHE_NAME = "testCache";
@Before
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册