下面的例子演示了使用EntryProcessor自动增加缓存条目的值。
CachingProvider provider = Caching.getCachingProvider();
CacheManager manager = provider.getCacheManager();
MutableConfiguration
new MutableConfiguration
.setTypes(String.class, Integer.class);
manager.createCache("example", configuration);
Cache
"example", configuration);
String key = "counter";
cache.put(key, 1);
int previous = cache.invoke(key,
newIncrementProcessor
assert previous == 1;
assert cache.get(key) == 2;
IncrementProcessor定义如下。
public static class IncrementProcessor
implements Cache.EntryProcessor
@Override
public Integer process(Cache.MutableEntry
Object... arguments){
if (entry.exists()) {
Integer current = entry.getValue();
entry.setValue(current + 1);
return current;
} else {
entry.setValue(0);
return -1;
}
}
}
支持远程或分布式缓存拓扑的实现可以选择在远程进程中执行条目处理器。在这种情况下实现可能需要获取EntryProcessors,调用的参数和返回类型实现java.lang.Serializable或以某种方式序列化。另外一个可选方法是实现可以选择简单序列化EntryProcessor类名,连同指定的调用参数,通过在远程实例化EntryProcessor类和反序列化调用的参数来执行远程调用请求。
当一个EntryProcessor被调用时,一个应用程序将永远不会看到其调用MutableEntry的getValue,etValue, remove方法产生的中间事件或副作用,而只能观察一个EntryProcessor上对缓存条目进行操作的最终结果。