代码##
ExecutorService es = Executors.newFixedThreadPool(2);
//带线程池的异步接口
cc.create().inBackground((client,event)->{
//pool-3-thread-1,CuratorEventImpl{type=CREATE, resultCode=0, path='/abc', name='/abc', children=null, context=null,stat=114,114,1573797468244,1573797468244,0,0,0,0,13,0,114, data=null, watchedEvent=null, aclList=null, opResults=null}
System.out.println(Thread.currentThread().getName()+","+event);
},es).forPath("/abc");
//不带线程池的异步接口
cc.delete().inBackground((client,event)->{
//main-EventThread,CuratorEventImpl{type=DELETE, resultCode=0, path='/abc', name='null', children=null, context=null, stat=null, data=null, watchedEvent=null, aclList=null, opResults=null}
System.out.println(Thread.currentThread().getName()+","+event);
}).forPath("/abc");
Thread.sleep(Integer.MAX_VALUE);
概念##
1.inBackground() 该方法就是添加一个异步的回调方法,参数是BackgroundCallback接口,是一个函数式接口。
2.BackgroundCallback的接口参数为client(当前客户端实例)及event(服务端事件)
3.事件类型,CuratorEventType,
包含如下信息 {type=DELETE, resultCode=0, path='/abc', name='null', children=null, context=null, stat=null, data=null, watchedEvent=null, aclList=null, opResults=null}
type对应的就是操作类型,比如delete对应的delete(),create对应create()等,resultCode是响应码,0代表成功
4.线程池es的作用,通过名称可以看到,默认情况下都是使用main-EventThread线程来串行执行,如果耗时较长会有影响,可以通过定制线程池来缓解这种情况。