TASK:异步调用generate及取消generate

This commit is contained in:
2024-01-24 11:43:56 +08:00
parent a9ce35200c
commit 96858c2cc3
10 changed files with 159 additions and 112 deletions

View File

@@ -14,7 +14,7 @@ import java.util.concurrent.*;
@Component
public class AsyncCallerUtil {
public static Map<Long, Boolean> waitingStatus = new HashMap<>();
public static Map<String, Boolean> waitingStatus = new HashMap<>();
private static PythonService pythonService;
@@ -27,9 +27,10 @@ public class AsyncCallerUtil {
return CompletableFuture.supplyAsync(() -> pythonService.generateSketchOrPrint(generateToPython));
}
public List<String> generate(GenerateToPythonDTO generateToPython, Long requestId) {
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
waitingStatus.put(requestId, true);
public List<String> generate(GenerateToPythonDTO generateToPython) {
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5);
String taskId = generateToPython.getTasks_id();
waitingStatus.put(taskId, true);
ScheduledFuture<?> timeoutTask = null;
try {
@@ -37,10 +38,10 @@ public class AsyncCallerUtil {
// 10秒后第一次确认之后每隔10秒确认一次用户选择结果
timeoutTask = scheduledExecutorService.scheduleAtFixedRate(() -> {
// 调用另一个接口获取用户的选择
if (!waitingStatus.get(requestId)) {
if (!waitingStatus.get(taskId)) {
// 如果用户选择取消则取消对generate的调用cancel判断是否成功取消
generateResult.cancel(true);
waitingStatus.remove(requestId);
waitingStatus.remove(taskId);
}
System.out.println("持续等待...... : " + DateUtil.getByTimeZone("Asia/Shanghai"));
}, 10, 10, TimeUnit.SECONDS);
@@ -54,16 +55,15 @@ public class AsyncCallerUtil {
// 处理结果
System.out.println("generate 响应: " + result);
System.out.println("schedule finish time : " + DateUtil.getByTimeZone("Asia/Shanghai"));
waitingStatus.remove(requestId);
waitingStatus.remove(taskId);
return result;
} catch (InterruptedException | ExecutionException | BusinessException e) {
// 处理异常
log.error("发生错误 " + e);
e.printStackTrace();
// 取消定时任务
assert timeoutTask != null;
timeoutTask.cancel(true);
throw new BusinessException("generate.interface.error");
throw new BusinessException(e.getMessage());
} finally {
// 关闭线程池
// executorService.shutdown();