场景:底层提供三个批量获取qq和微信的相关信息接口。都是通过dtcServiceFuture.calculate(List,Map)函数获取。由于业务场景规定在五秒内获取要求获取大量的QQ好友和微信好友数据信息,所有采用多线程方式获取数据。
dtcServiceFuture是一个异步调用Future对象
主要流程为:
第一阶段:采用Future对象将所有数据按照200为一组建立一个单线程,采用Future的好处在于,Futuer对象在建立期间,其他Future对象会在并行计算。
List<Future> friendsNetInfoFutureList = new ArrayList<Future>(); List<Future> friendsLevelInfoFutureList = new ArrayList<Future>(); List<Future> friendsDpInfoFutureList = new ArrayList<Future>(); for(List<Integer> batchUserIds : compentList){ Map<String, Object> contextMap = new HashMap<String, Object>(); contextMap.put("userIds", batchUserIds); friendsNetInfoFutureList.add(getFuture(qq_wechat.get(type), contextMap)); friendsLevelInfoFutureList.add(getFuture(serviceKey[0], contextMap)); friendsDpInfoFutureList.add(getFuture(serviceKey[1], contextMap)); }第二阶段:第一阶段建立的N个线程在不断并行执行,Future.get函数会等到所有future任务完全执行完毕后进行获取结果,采用Future的第二个好处在于可以获取返回结果。
List<HashMap<String,String>> friendsNetInfo = new ArrayList<HashMap<String, String>>(); HashMap<String, HashMap<String,String>> friendsLevelInfo = new HashMap<String, HashMap<String, String>>(); List<HashMap<String,String>> friendsDpInfo = new ArrayList<HashMap<String, String>>(); for(int i = 0; i < compentList.size();i++){ Object temp; //根据用户id查询QQ或者微信号和昵称,qq号或者微信昵称可能会有多个 temp = getInfo(qq_wechat.get(type), friendsNetInfoFutureList.get(i)); if(temp != null){ friendsNetInfo.addAll((List)temp); } //根据用户id获取星级 temp = getInfo(serviceKey[0], friendsLevelInfoFutureList.get(i)); if(temp != null){ friendsLevelInfo.putAll((HashMap)temp); } // 根据用户查询用户昵称 temp = getInfo(serviceKey[1], friendsDpInfoFutureList.get(i)); if(temp != null){ friendsDpInfo.addAll((List)temp); } }