一、互联网项目的特性
现今的互联网项目具有以下特点:
1、前后端分离,多样化;
2、后端使用分布式系统支撑;
3、移动端尽量减少和后端的交互;
4、同样的信息在不同的页面有不同的展示。
为了减少移动端和后端的交互,减少定制化的接口,后端通过网关进行接口聚合。架构图如下:

二、统一网关并行调用分布式系统接口
为了缩短响应时间,网关对于分布式系统接口的调用可以并行进行,接口数据都返回后,将结果组成返回。响应时间取决于调用最慢的接口。模拟代码(获取用户和积分信息后返回)如下:
Callable <JSONObject> queryUserInfoCallable = new Callable<JSONObject>(){
public JSONObject call() throws Exception{
String value = httpService.queryUserInfo(userId);
JSONObject userInfo = JSONObject.parseObject(value );
return userInfo;
}
}
FuttureTask<JSONObject> userInfoTask = new FuttureTask<JSONObject >(queryUserInfoCallable );
Callable <JSONObject> queryIntergralrInfoCallable = new Callable< JSONObject >(){
public JSONObject call() throws Exception{
String value = httpService.queryIntergralInfo(userId);
JSONObject intergralInfo = JSONObject.parseObject( value );
return intergralInfo ;
}
}
FutureTask< JSONObject > intergralInfoTask = new FuttureTask< JSONObject >(queryIntergralrInfoCallable);
new Thread(userInfoTask).start();
new Thread(intergralInfoTask).start();
JSONObject result = new JSONObject();
result.putAll(userInfoTask.get());
result.putAll(intergralInfoTask.get());
return result;
当调用 futureTask的get方法时,会阻塞当前线程,直到有结果返回。
三、Future类结构图

下面以流程图的方式介绍每个方法的执行流程。
四、FutureTask关键方法执行流程
1、Run方法执行流程

2、Cancel方法执行流程

3、Get方法执行流程

线程的挂起和唤醒是通过LockSupport的park和unPark方法来实现的。finishCompletion 方法会调用 unPark方法唤醒挂起的线程。
网友评论