利用Callable返回结果异步任务

MyUploadCallable callable = new MyUploadCallable(map, key, img);
FutureTask<Map<String, Object>> futureTask = new FutureTask<Map<String, Object>>(callable);
MyFactory.createMyExecutor().execute(futureTask);
Map<String, Object> uploadMap = futureTask.get();

MyUploadCallable就是一个实现了Callable的实现类

class MyUploadCallable implements Callable<Map<String, Object>> {
private String key;
private String img;
private Map<String, Object> map;

public MyUploadCallable(Map<String, Object> map, String key, String img) {
this.key = key;
this.img = img;
this.map = map;
}

@Override
public Map<String, Object> call() throws Exception {
if (null != img && !img.isEmpty()) {
FileDO byFileId = fileDAO.getByFileId(img);
img = byFileId != null ? byFileId.getPath() : img;
AliOSSUtil aliOSSUtil = new AliOSSUtil(systemConfig.getOssEndPoint(), systemConfig.getOssAccessId(), systemConfig.getOssAccessKey());
String s = aliOSSUtil.fileUrl(systemConfig.getBucketNameFiles(), img);
String url = s.substring(0, s.lastIndexOf("?"));
Map<String, Object> filemap = new HashMap<>();

String filePath = uploadFile(url);
if ("".equals(filePath)) {
logger.info("图片下载失败 >> picturePath : " + img);
return map;
}
File file = new File(filePath);
String value = DigestUtils.md5Hex(FileUtils.readFileToByteArray(file));
filemap.put("fileMD5", value);
//调用乐刷
Map<String, String> retMap = reqPictureUpload(filemap, systemConfig.getBrushEntryKey(), systemConfig.getBrushPictureUpload(), systemConfig.getBrushAgentId(), filePath);
//删除图片
file.delete();
if (null != retMap && "000000".equals(retMap.get("respCode"))) {
String photoUrl = retMap.get("photoUrl");
map.put(key, photoUrl);
}
}
return map;
}
}
public class MyFactory {
private final static Logger logger = LoggerFactory.getLogger(MyFactory.class);
static ThreadPoolExecutor executor = null;

public static synchronized ThreadPoolExecutor createMyExecutor() {
if (executor == null) {
logger.info("create executor, num={}", ComConstants.num);

BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(100);
executor = new ThreadPoolExecutor(ComConstants.num,
ComConstants.num, 1, TimeUnit.HOURS, queue, new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
} else {
return executor;
}


}
}

发表评论

邮箱地址不会被公开。