我正在尝试使用下面的代码为Ehcache 3.3.1项目实现一个监听器。任何人都可以为ListenerObject建议一个解决方案吗?我无法在任何地方找到它,除了docs page我从
获取代码import java.util.logging.Level;
import java.util.logging.Logger;
import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheEventListenerConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.event.EventType;
public class CacheHandler{
private Logger LOG = Logger.getLogger(this.getClass().getName());
private String cacheName="basicCache";
public Cache cache;
public CacheHandler(){
if(cache==null)
cache=initCache();
}
private Cache initCache(){
CacheEventListenerConfigurationBuilder cacheEventListenerConfiguration = CacheEventListenerConfigurationBuilder
.newEventListenerConfiguration(new ListenerObject(), EventType.CREATED, EventType.UPDATED)
.unordered().asynchronous();
final CacheManager manager = CacheManagerBuilder.newCacheManagerBuilder()
.withCache(cacheName,
CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class, ResourcePoolsBuilder.heap(10))
.add(cacheEventListenerConfiguration)
).build(true);
final Cache<String, String> cache = manager.getCache("foo", String.class, String.class);
return cache;
}
public Cache getCache(){
if(cache==null)
cache=initCache();
return cache;
}
}
答案 0 :(得分:3)
确实没有提及,但由于它只是一种方法,因此通常很容易弄明白。
以下是一个例子:
public class ListenerObject implements CacheEventListener<Object, Object> {
@Override
public void onEvent(CacheEvent<? extends Object, ? extends Object> event) {
System.out.println(event);
}
}
文档中使用的真实内容是here。
然后,我用你的代码玩了一些真实的生产可用代码。
public class CacheHandler implements AutoCloseable {
private static final String CACHE_NAME = "basicCache";
private final Cache<String, String> cache;
private final CacheManager cacheManager;
public CacheHandler() {
cacheManager = initCacheManager();
cache = cacheManager.getCache(CACHE_NAME, String.class, String.class);
}
private CacheManager initCacheManager(){
CacheEventListenerConfigurationBuilder cacheEventListenerConfiguration = CacheEventListenerConfigurationBuilder
.newEventListenerConfiguration(new ListenerObject(), EventType.CREATED, EventType.UPDATED)
.ordered().synchronous();
return CacheManagerBuilder.newCacheManagerBuilder()
.withCache(CACHE_NAME,
CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class, ResourcePoolsBuilder.heap(10))
.add(cacheEventListenerConfiguration)
).build(true);
}
public Cache getCache(){
return cache;
}
@Override
public void close() {
cacheManager.close();
}
public static void main(String[] args) {
try(CacheHandler handler = new CacheHandler()) {
Cache<String, String> cache = handler.getCache();
cache.put("a", "b");
cache.putIfAbsent("a", "c");
}
}
}
一些意见:
initCache
没用,因为withCache
告诉Ehcache在创建缓存管理器时创建缓存。CacheManager
的引用,以便在最后关闭它。getCache
正在检索“foo”,而不是“basicCache”