package com.taobao.pagani.huntingnew.biz.benefit.check;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import com.taobao.eagleeye.EagleEye;
import com.taobao.pagani.huntingnew.common.threadpool.ThreadPoolExecutorFactory;
import com.taobao.pagani.huntingnew.common.util.logger.LoggerUtil;
import com.taobao.pagani.huntingnew.pipeline.spi.PipelineContext;
import com.taobao.pagani.huntingnew.switchs.PaganiSwitchConfig;
import com.taobao.uic.common.domain.BaseUserDO;
import jodd.exception.ExceptionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
/**
*
* @author zhenyuan.he
* @version $Id: InfactDataBatchEngine.java, v 0.1 2018年8月29日 下午8:44:11 zhenyuan.he Exp $
*/
public class BatchCheckEngine {
protected static final Logger logger = LoggerFactory.getLogger(BatchCheckEngine.class);
/**
* 异步多线程调用
* @param benefitChecks
* @param baseUserDO
* @param sceneId
* @param extraParam
* @return
*/
public static boolean asynExecuteTask(Map<String, BenefitCheck> benefitChecks,
BaseUserDO baseUserDO, long sceneId,
Map<String, Object> extraParam) {
Future<Boolean> excuteFuture = null;
try {
if (CollectionUtils.isEmpty(benefitChecks)) {
LoggerUtil.info(logger, "parallelExecuteTask is null,benefitChecks is null");
return true;
}
ThreadPoolExecutor threadPoolExecutor = ThreadPoolExecutorFactory.getInstance();
List<Future<Boolean>> futures = new ArrayList<>();
for (Entry<String, BenefitCheck> benefitCheck : benefitChecks.entrySet()) {
CheckTask checkTask = new CheckTask(benefitCheck.getValue(), baseUserDO, sceneId,
extraParam, EagleEye.getRpcContext());
Future<Boolean> future = threadPoolExecutor.submit(checkTask);
if (future != null) {
futures.add(future);
}
}
for (int index = 0; index < futures.size(); index++) {
excuteFuture = futures.get(index);
Boolean infactData = excuteFuture.get(PaganiSwitchConfig.CHECK_TASK_TIME_OUT,
TimeUnit.MILLISECONDS);
if (infactData != null && !infactData) {
return false;
}
}
return true;
} catch (TimeoutException timeoutException) {
// 超时异常不打日志
PipelineContext.addDebugLog("校验超时,错误详情",
ExceptionUtil.exceptionChainToString(timeoutException).substring(0, 200));
return false;
} catch (Throwable e) {
if (excuteFuture != null) {
excuteFuture.cancel(true);
}
LoggerUtil.error(logger, e, "parallelExecuteTask error,userId=", baseUserDO.getUserId(),
"sceneId=", sceneId, "extraParam=", extraParam);
return false;
}
}
}