Infinispan-API之异步(一)

2022-04-14 00:00:00 专区 订阅 添加 将会 会有

   在Infinispan中出了同步API以外自然会有异步API,例如:Cache.putAsync()、Cache.removeAsync()

会返回一个Future结果集。例如:Cache<String,String>,Cache.put(Stirng key,String value),将会返回一个String,同时Cache.putAsync(String key,String value);将会返回一个Future<String>.

1、API例子使用说明:

Set<Future<?>> futures = new HashSet<Future<?>>();
futures.add(cache.putAsync(key1, value1)); // does not block
futures.add(cache.putAsync(key2, value2)); // does not block
futures.add(cache.putAsync(key3, value3)); // does not block

// the remote calls for the 3 puts will effectively be executed
// in parallel, particularly useful if running in distributed mode
// and the 3 keys would typically be pushed to 3 different nodes
// in the cluster

// check that the puts completed successfully
for (Future<?> f: futures) f.get();
2、自然这个API被调用完毕会有一个疑问我怎么知道这个东西一定被添加到缓存成功了呢啊!
Infinispan给出的解决方案是添加一个侦听器,来坚挺添加成功后的的事件。
FutureListener futureListener = new FutureListener() {

public void futureDone(Future future) {
try {
future.get(); //如果添加成功,会触发这个事件。
} catch (Exception e) {
// Future did not complete successfully
//添加异常后会抛出异常信息
System.out.println( "Help!" );
}
}
};

cache.putAsync( "key" , "value" ).attachListener(futureListener);

相关文章