接口定义
public interface DownloadTaskExecutor {
void run(Integer taskId , String params);
}
工厂类
import java.util.HashMap;
import java.util.Map;
public class DownloadTaskExecutorFactory {
private static Map<String, DownloadTaskExecutor> CALL_BACK_REGISTERS = new HashMap<>();
public static void register(String code, DownloadTaskExecutor taskExecutor) {
if (null != code ) {
CALL_BACK_REGISTERS.put(code, taskExecutor);
}
}
public static DownloadTaskExecutor get(String code) {
return CALL_BACK_REGISTERS.get(code);
}
public static Boolean isRegister(String code) {
return CALL_BACK_REGISTERS.containsKey(code);
}
}
业务实现:
import javax.annotation.PostConstruct;
@Service
public class ExportSupplierListTask implements DownloadTaskExecutor {
@Autowired
private SaSupplierExportLogic saSupplierExportLogic;
@PostConstruct
public void init() {
DownloadTaskExecutorFactory.register(ServiceApiFileServiceDownloadTaskManagerConstant.BUSINESS_KEY_ART_BUSINESS_SUPPLIER_LIST, this);
}
@Override
public void run(Integer taskId, String params) {
SupplierExportForm form = JSONObject.parseObject(params, SupplierExportForm.class);
saSupplierExportLogic.exportSupplierList(taskId, form);
}
}
业务调用
@Override
@Async("fooThreadPool")
public void assign(Integer taskId, String businessKey, String params) {
log.info("======DownloadTask任务开始执行,taskId:"+taskId+";businessKey:"+businessKey+"======");
if(DownloadTaskExecutorFactory.isRegister(businessKey)){
DownloadTaskExecutorFactory.get(businessKey).run(taskId, params);
}else {
try {
// 延时5秒
Thread.sleep(5000);
serviceApiFileDownLoadTaskManagerService.errorReport(taskId, "该业务类型的处理程序没有注册");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
log.info("======DownloadTask任务执行结束,taskId:"+taskId+";businessKey:"+businessKey+"======");
}