| | |
| | | package com.linghu.controller; |
| | | |
| | | import java.time.LocalDateTime; |
| | | import java.time.format.DateTimeFormatter; |
| | | import java.util.ArrayList; |
| | | import java.util.Date; |
| | | import java.util.List; |
| | |
| | | import org.springframework.web.reactive.function.client.WebClient; |
| | | import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; |
| | | |
| | | import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; |
| | | import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; |
| | | import com.linghu.model.common.ResponseResult; |
| | | import com.linghu.model.dto.HealthResponse; |
| | | import com.linghu.model.dto.SearchTaskRequest; |
| | | import com.linghu.model.entity.Keyword; |
| | | import com.linghu.model.entity.Question; |
| | |
| | | import com.linghu.model.dto.SearchTaskResponse; |
| | | import com.linghu.model.dto.TaskStatusResponse; |
| | | import com.linghu.model.dto.TaskCancelResponse; |
| | | import com.linghu.model.dto.TaskListResponse; |
| | | |
| | | import io.jsonwebtoken.lang.Collections; |
| | | import io.swagger.annotations.Api; |
| | |
| | | return Mono.just(ResponseResult.error(500, "取消任务失败: " + e.getMessage())); |
| | | }); |
| | | } |
| | | // @ApiOperation(value = "获取任务结果") |
| | | // @GetMapping("/tasks/{taskId}/result") |
| | | // public Mono<ResponseResult<TaskResultResponse>> getTaskResult(@PathVariable |
| | | // String taskId) { |
| | | // return webClient.get() |
| | | // .uri(baseUrl + "/tasks/" + taskId + "/result") |
| | | // .retrieve() |
| | | // .onStatus(HttpStatus::isError, response -> response.bodyToMono(String.class) |
| | | // .flatMap(errorBody -> Mono.error(new RuntimeException("获取结果失败: " + |
| | | // errorBody)))) |
| | | // .bodyToMono(TaskResultResponse.class) |
| | | // .flatMap(result -> { |
| | | // // 更新keyword状态 |
| | | // LambdaUpdateWrapper<Keyword> keywordWrapper = new LambdaUpdateWrapper<>(); |
| | | // keywordWrapper.eq(Keyword::getTask_id, taskId) |
| | | // .set(Keyword::getStatus, "completed"); |
| | | // keywordService.update(keywordWrapper); |
| | | |
| | | // // 更新question信息并收集references |
| | | // List<Question> updateQuestions = new ArrayList<>(); |
| | | // List<Reference> references = new ArrayList<>(); |
| | | @ApiOperation(value = "获取任务结果") |
| | | @GetMapping("/tasks/{taskId}") |
| | | public Mono<ResponseResult<TaskResultResponse>> getTaskResult(@PathVariable String taskId) { |
| | | return webClient.get() |
| | | .uri(baseUrl + "/tasks/" + taskId + "/result") |
| | | .accept(MediaType.APPLICATION_JSON) |
| | | .retrieve() |
| | | .onStatus(HttpStatus::is4xxClientError, response -> { |
| | | if (response.statusCode() == HttpStatus.NOT_FOUND) { |
| | | return response.bodyToMono(String.class) |
| | | .flatMap(errorBody -> Mono.error(new RuntimeException("任务不存在"))); |
| | | } else if (response.statusCode() == HttpStatus.BAD_REQUEST) { |
| | | return response.bodyToMono(String.class) |
| | | .flatMap(errorBody -> Mono.error(new RuntimeException("任务未完成,无法获取结果"))); |
| | | } |
| | | return response.createException().flatMap(Mono::error); |
| | | }) |
| | | .bodyToMono(new ParameterizedTypeReference<ResponseResult<TaskResultResponse>>() { |
| | | }) |
| | | .flatMap(responseResult -> { |
| | | TaskResultResponse result = responseResult.getData(); |
| | | if (result != null && result.getResults() != null) { |
| | | return updateQuestionAndReference(result) |
| | | .thenReturn(responseResult); |
| | | } |
| | | return Mono.just(responseResult); |
| | | }) |
| | | .onErrorResume(e -> { |
| | | System.out.println("获取任务结果失败"); |
| | | return Mono.just(ResponseResult.error(e.getMessage())); |
| | | }); |
| | | } |
| | | |
| | | // result.getResults().forEach(userResult -> { |
| | | // userResult.getQuestions_results().forEach(qResult -> { |
| | | // Question question = new Question(); |
| | | // question.setQuestion_id(qResult.getQuestion_id()); |
| | | // question.setResponse(qResult.getResponse()); |
| | | // question.setStatus(qResult.getStatus()); |
| | | // updateQuestions.add(question); |
| | | /* |
| | | * private Mono<Void> updateQuestionAndReference(TaskResultResponse result) { |
| | | * return Mono.fromRunnable(() -> { |
| | | * // 1. 更新关键词状态 |
| | | * LambdaUpdateWrapper<Keyword> keywordUpdate = new LambdaUpdateWrapper<>(); |
| | | * keywordUpdate.eq(Keyword::getTask_id, result.getTask_id()) |
| | | * .set(Keyword::getStatus, "completed"); |
| | | * keywordService.update(keywordUpdate); |
| | | * |
| | | * // 查询关键词ID |
| | | * LambdaQueryWrapper<Keyword> keywordQuery = new LambdaQueryWrapper<>(); |
| | | * keywordQuery.eq(Keyword::getTask_id, result.getTask_id()); |
| | | * Keyword keyword = keywordService.getOne(keywordQuery); |
| | | * |
| | | * if (keyword == null) { |
| | | * System.out.println("未找到关联的关键词,task_id: " + result.getTask_id()); |
| | | * return; |
| | | * } |
| | | * |
| | | * // 2. 处理每个用户的问题结果 |
| | | * for (UserResult userResult : result.getResults()) { |
| | | * for (QuestionResult questionResult : userResult.getQuestions_results()) { |
| | | * // 2.1 查询问题ID |
| | | * LambdaQueryWrapper<Question> queryWrapper = new LambdaQueryWrapper<>(); |
| | | * queryWrapper.eq(Question::getQuestion, questionResult.getQuestion()) |
| | | * .eq(Question::getKeyword_id, keyword.getKeyword_id()); |
| | | * Question question = questionService.getOne(queryWrapper); |
| | | * |
| | | * if (question != null) { |
| | | * // 更新问题状态 |
| | | * LambdaUpdateWrapper<Question> updateWrapper = new LambdaUpdateWrapper<>(); |
| | | * updateWrapper.eq(Question::getQuestion_id, question.getQuestion_id()) |
| | | * .set(Question::getStatus, questionResult.getStatus()) |
| | | * .set(Question::getResponse, questionResult.getResponse()) |
| | | * .set(Question::getExtracted_count, questionResult.getExtracted_count()) |
| | | * .set(Question::getError, questionResult.getError()) |
| | | * .set(Question::getTimestamp, LocalDateTime.parse( |
| | | * questionResult.getTimestamp(), |
| | | * DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSS") |
| | | * )); |
| | | * questionService.update(updateWrapper); |
| | | * |
| | | * // 2.2 保存引用数据 |
| | | * List<Reference> references = questionResult.getReferences().stream() |
| | | * .map(ref -> { |
| | | * Reference reference = new Reference(); |
| | | * reference.setQuestion_id(question.getQuestion_id()); |
| | | * reference.setTitle(ref.getTitle()); |
| | | * reference.setUrl(ref.getUrl()); |
| | | * reference.setDomain(ref.getDomain()); |
| | | * reference.setCreate_time(new Date()); |
| | | * return reference; |
| | | * }) |
| | | * .collect(Collectors.toList()); |
| | | * |
| | | * if (!references.isEmpty()) { |
| | | * referenceService.saveBatch(references); |
| | | * } |
| | | * } else { |
| | | * System.out.println("未找到匹配的问题,question " + question.getQuestion()); |
| | | * |
| | | * } |
| | | * } |
| | | * } |
| | | * }); |
| | | * } |
| | | */ |
| | | |
| | | // // 转换references |
| | | // references.addAll(qResult.getReferences().stream() |
| | | // .map(ref -> new Reference( |
| | | // qResult.getQuestion_id(), |
| | | // ref.getTitle(), |
| | | // ref.getUrl(), |
| | | // ref.getDomain(), |
| | | // result.getTask_id(), |
| | | // )) |
| | | // .collect(Collectors.toList())); |
| | | // }); |
| | | // }); |
| | | private Mono<Void> updateQuestionAndReference(TaskResultResponse result) { |
| | | return Mono.fromRunnable(() -> { |
| | | try { |
| | | // 1. 更新关键词状态 |
| | | LambdaUpdateWrapper<Keyword> keywordUpdate = new LambdaUpdateWrapper<>(); |
| | | keywordUpdate.eq(Keyword::getTask_id, result.getTask_id()) |
| | | .set(Keyword::getStatus, "completed"); |
| | | keywordService.update(keywordUpdate); |
| | | |
| | | // // 批量更新和插入 |
| | | // if (!updateQuestions.isEmpty()) { |
| | | // questionService.updateBatchById(updateQuestions); |
| | | // } |
| | | // if (!references.isEmpty()) { |
| | | // referenceService.saveBatch(references); |
| | | // } |
| | | // 查询关键词ID |
| | | LambdaQueryWrapper<Keyword> keywordQuery = new LambdaQueryWrapper<>(); |
| | | keywordQuery.eq(Keyword::getTask_id, result.getTask_id()); |
| | | Keyword keyword = keywordService.getOne(keywordQuery); |
| | | |
| | | // return Mono.just(ResponseResult.success(result)); |
| | | // }) |
| | | // .onErrorResume(e -> Mono.just(ResponseResult.error(e.getMessage()))); |
| | | // } |
| | | if (keyword == null) { |
| | | // log.error("未找到关联的关键词,task_id: {}", result.getTask_id()); |
| | | System.out.println("未找到关联的关键词,task_id: " + result.getTask_id()); |
| | | return; |
| | | } |
| | | |
| | | // @ApiOperation(value = "获取任务结果") |
| | | // @GetMapping("/tasks/{taskId}/result") |
| | | // public Mono<ResponseResult<TaskResultResponse>> |
| | | // getTaskResultlMono(@PathVariable String taskId) { |
| | | // return webClient.get() |
| | | // .uri(baseUrl + "/tasks/" + taskId + "/result") |
| | | // .accept(MediaType.APPLICATION_JSON) |
| | | // .retrieve() |
| | | // .onStatus(HttpStatus::is4xxClientError, response -> { |
| | | // if (response.statusCode() == HttpStatus.NOT_FOUND) { |
| | | // return response.bodyToMono(String.class) |
| | | // .flatMap(errorBody -> Mono.error(new RuntimeException("任务不存在"))); |
| | | // } else if (response.statusCode() == HttpStatus.BAD_REQUEST) { |
| | | // return response.bodyToMono(String.class) |
| | | // .flatMap(errorBody -> Mono.error(new RuntimeException("任务未完成,无法获取结果"))); |
| | | // } |
| | | // return response.createException().flatMap(Mono::error); |
| | | // }) |
| | | // .bodyToMono(new |
| | | // ParameterizedTypeReference<ResponseResult<TaskResultResponse>>() {}) |
| | | // .flatMap(responseResult -> { |
| | | // TaskResultResponse result = responseResult.getData(); |
| | | // if (result != null && result.getResults() != null) { |
| | | // // 处理结果并更新数据库 |
| | | // return updateQuestionAndReference(result) |
| | | // .thenReturn(responseResult); |
| | | // } |
| | | // return Mono.just(responseResult); |
| | | // }) |
| | | // .onErrorResume(e -> { |
| | | // 2. 批量查询所有问题(假设Question有task_id和keyword_id字段) |
| | | LambdaQueryWrapper<Question> queryWrapper = new LambdaQueryWrapper<>(); |
| | | queryWrapper.eq(Question::getKeyword_id, keyword.getKeyword_id()); |
| | | List<Question> questions = questionService.list(queryWrapper); |
| | | |
| | | // return Mono.just(ResponseResult.error(e.getMessage())); |
| | | // }); |
| | | // } |
| | | // 构建问题映射表,用于快速查找 |
| | | Map<String, Question> questionMap = questions.stream() |
| | | .collect(Collectors.toMap(Question::getQuestion, q -> q)); |
| | | |
| | | // 更新问题和引用数据 |
| | | // private Mono<Void> updateQuestionAndReference(TaskResultResponse result) { |
| | | // return Mono.fromRunnable(() -> { |
| | | // // 1. 更新关键词状态 |
| | | // LambdaUpdateWrapper<Keyword> keywordUpdate = new LambdaUpdateWrapper<>(); |
| | | // keywordUpdate.eq(Keyword::getTask_id, result.getTask_id()) |
| | | // .set(Keyword::getStatus, "completed"); |
| | | // keywordService.update(keywordUpdate); |
| | | // 3. 收集所有需要更新的问题和引用 |
| | | List<Question> questionsToUpdate = new ArrayList<>(); |
| | | List<Reference> allReferences = new ArrayList<>(); |
| | | |
| | | // // 2. 处理每个用户的问题结果 |
| | | // for (UserResult userResult : result.getResults()) { |
| | | // for (QuestionResult questionResult : userResult.getQuestions_results()) { |
| | | // // 2.1 更新问题状态 |
| | | // LambdaUpdateWrapper<Question> questionUpdate = new LambdaUpdateWrapper<>(); |
| | | // questionUpdate.eq(Question::getTa, result.getTask_id()) |
| | | // .eq(Question::getContent, questionResult.getQuestion()) |
| | | // .set(Question::getStatus, questionResult.getStatus()) |
| | | // .set(Question::getResponse, questionResult.getResponse()) |
| | | // .set(Question::getProcessTime, |
| | | // LocalDateTime.parse(questionResult.getTimestamp())); |
| | | // questionService.update(questionUpdate); |
| | | // 遍历结果,只收集数据不执行数据库操作 |
| | | for (UserResult userResult : result.getResults()) { |
| | | for (QuestionResult questionResult : userResult.getQuestions_results()) { |
| | | try { |
| | | Question question = questionMap.get(questionResult.getQuestion()); |
| | | if (question != null) { |
| | | // 更新问题对象 |
| | | question.setStatus(questionResult.getStatus()); |
| | | question.setResponse(questionResult.getResponse()); |
| | | question.setExtracted_count(questionResult.getExtracted_count()); |
| | | question.setError(questionResult.getError()); |
| | | |
| | | // // 2.2 保存引用数据 |
| | | // List<Reference> references = questionResult.getReferences().stream() |
| | | // .map(ref -> { |
| | | // Reference reference = new Reference(); |
| | | // reference.setQuestionId(questionService.getOne(questionUpdate).getId()); |
| | | // reference.setTitle(ref.getTitle()); |
| | | // reference.setUrl(ref.getUrl()); |
| | | // reference.setDomain(ref.getDomain()); |
| | | // reference.setCreateTime(LocalDateTime.now()); |
| | | // return reference; |
| | | // }) |
| | | // .collect(Collectors.toList()); |
| | | // 解析时间戳 |
| | | if (questionResult.getTimestamp() != null) { |
| | | DateTimeFormatter formatter = DateTimeFormatter |
| | | .ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSS"); |
| | | question.setTimestamp( |
| | | LocalDateTime.parse(questionResult.getTimestamp(), formatter)); |
| | | } |
| | | |
| | | // if (!references.isEmpty()) { |
| | | // referenceService.saveBatch(references); |
| | | // } |
| | | // } |
| | | // } |
| | | // }); |
| | | // } |
| | | questionsToUpdate.add(question); |
| | | |
| | | // 收集引用数据 |
| | | List<Reference> references = questionResult.getReferences().stream() |
| | | .map(ref -> { |
| | | Reference reference = new Reference(); |
| | | reference.setQuestion_id(question.getQuestion_id()); |
| | | reference.setTitle(ref.getTitle()); |
| | | reference.setUrl(ref.getUrl()); |
| | | reference.setDomain(ref.getDomain()); |
| | | reference.setCreate_time(LocalDateTime.now()); |
| | | return reference; |
| | | }) |
| | | .collect(Collectors.toList()); |
| | | |
| | | allReferences.addAll(references); |
| | | } else { |
| | | // log.warn("未找到匹配的问题,question: {}, keyword_id: {}", |
| | | // questionResult.getQuestion(), keyword.getKeyword_id()); |
| | | } |
| | | } catch (Exception e) { |
| | | // log.error("处理问题结果失败,question: {}, error: {}", |
| | | // questionResult.getQuestion(), e.getMessage(), e); |
| | | } |
| | | } |
| | | } |
| | | |
| | | // 4. 批量更新问题 |
| | | if (!questionsToUpdate.isEmpty()) { |
| | | questionService.updateBatchById(questionsToUpdate); |
| | | // log.info("成功批量更新 {} 个问题", questionsToUpdate.size()); |
| | | } |
| | | |
| | | // 5. 批量插入引用 |
| | | if (!allReferences.isEmpty()) { |
| | | // 分批处理,每批1000条记录,避免内存溢出 |
| | | int batchSize = 1000; |
| | | for (int i = 0; i < allReferences.size(); i += batchSize) { |
| | | List<Reference> batch = allReferences.subList( |
| | | i, Math.min(i + batchSize, allReferences.size())); |
| | | referenceService.saveBatch(batch); |
| | | } |
| | | // log.info("成功批量插入 {} 条引用数据", allReferences.size()); |
| | | } |
| | | |
| | | } catch (Exception e) { |
| | | // log.error("更新问题和引用数据失败,task_id: {}, error: {}", |
| | | // result.getTask_id(), e.getMessage(), e); |
| | | throw new RuntimeException("更新问题和引用数据失败", e); |
| | | } |
| | | }); |
| | | } |
| | | |
| | | @GetMapping("/tasks/all") |
| | | @ApiOperation(value = "获取所有任务列表") |
| | | public Mono<ResponseResult<TaskListResponse>> getAllTasks() { |
| | | return webClient.get() |
| | | .uri(baseUrl + "/tasks") |
| | | .accept(MediaType.APPLICATION_JSON) |
| | | .retrieve() |
| | | .bodyToMono(new ParameterizedTypeReference<ResponseResult<TaskListResponse>>() { |
| | | }) |
| | | .onErrorResume(e -> { |
| | | return Mono.just(ResponseResult.error("获取任务列表失败: " + e.getMessage())); |
| | | }); |
| | | } |
| | | |
| | | @GetMapping("/health") |
| | | public Mono<HealthResponse> checkThirdPartyHealth() { |
| | | return webClient.get() |
| | | .uri(baseUrl + "/health") // 假设第三方健康检查接口路径为/health |
| | | .retrieve() |
| | | .bodyToMono(HealthResponse.class) |
| | | .onErrorResume(e -> Mono.just( |
| | | new HealthResponse("unhealthy", null, "", e.getMessage()))); |
| | | } |
| | | } |