上次写 Yar Java Client 需要执行异步并行请求的时候,跟好友明明获取到关键词ExecutorService
,记了一篇笔记 http://mengkang.net/596.html 今天再看,感觉等于没写,晕晕乎乎的,决定重新写记录下。
现在的需求就是用户注册成功之后,我需要给该用户到第三方平台注册一个关联的 IM 用户,提供后期的通讯功能。但是这个请求第三方的注册接口,比较耗时,所以希望异步化,最好是队列执行。所以选择ExecutorService
取代最原始的new Thread start
的写法。
把代码改成伪代码,方便自己复习和他人阅读
import java.util.concurrent.*; public class Test { private static ExecutorService executorService; static { executorService = Executors.newCachedThreadPool(); } public void register(int uid){ Future<Object> future = executorService.submit(new registerCallable(uid)); // TODO 注册失败的事件需要日志记录,后期重新注册 } public class registerCallable implements Callable<Object> { private int uid; public registerCallable(int uid) { this.uid = uid; } @Override public Object call() throws Exception { // 需要异步执行的逻辑 // 发送注册请求... String registerApi = "https://a1.easemob.com/topit/16pk/users"; return HttpRequestUtil.post(registerApi, this.uid); } } }
这里有一篇笔记写得简单明了 http://uule.iteye.com/blog/1488270 同时说明了 Callable 和 Runnable 的区别。