295 lines
12 KiB
Java
295 lines
12 KiB
Java
package com.ichangzuo.system.service.impl;
|
||
|
||
import com.ichangzuo.system.mapper.QnAMapper;
|
||
import com.ichangzuo.system.model.bo.QnAUpdateBO;
|
||
import com.ichangzuo.system.model.dto.*;
|
||
import com.ichangzuo.system.model.entity.QnA;
|
||
import com.ichangzuo.system.service.RagClientService;
|
||
import jakarta.annotation.PreDestroy;
|
||
import lombok.RequiredArgsConstructor;
|
||
import lombok.extern.slf4j.Slf4j;
|
||
import org.springframework.beans.factory.annotation.Value;
|
||
import org.springframework.scheduling.annotation.Scheduled;
|
||
import org.springframework.stereotype.Service;
|
||
|
||
import java.io.IOException;
|
||
import java.util.List;
|
||
import java.util.Set;
|
||
import java.util.concurrent.CountDownLatch;
|
||
import java.util.concurrent.TimeUnit;
|
||
import java.util.concurrent.atomic.AtomicLong;
|
||
import java.util.stream.Collectors;
|
||
|
||
/**
|
||
* 问题轮询服务 - 定时拉取未读问题并逐条处理
|
||
*
|
||
* <p>每 {@code polling.fixedDelay}ms 执行一次轮询,每次最多拉取
|
||
* {@code polling.batch-size} 条 state=0 的未读问题,
|
||
* 先批量置为 state=1(原子性领取),再逐条串行处理。</p>
|
||
*
|
||
* <p>线程模型:轮询调度器使用单线程(Spring {@code fixedDelay} 保证),
|
||
* 所有问题在该线程上串行执行。{@code @PreDestroy} 在独立的 JVM 关闭线程上运行。</p>
|
||
*/
|
||
@Slf4j
|
||
@Service
|
||
@RequiredArgsConstructor
|
||
public class QuestionPollingService {
|
||
|
||
private final QnAMapper qnAMapper;
|
||
private final QnAServiceImpl qnaService;
|
||
private final RagClientService ragClientService;
|
||
|
||
@Value("${polling.batch-size:10}")
|
||
private int batchSize;
|
||
|
||
/** 在途问题计数器 — 调度线程递增/递减,shutdown 线程读取 */
|
||
private final AtomicLong inFlightCount = new AtomicLong(0);
|
||
|
||
/**
|
||
* 优雅关闭用 CountDownLatch(初始计数 1,表示"尚未完成")。
|
||
* <p>当 {@link #shutdownRequested} 为 true 且 {@link #inFlightCount} 降为 0 时
|
||
* (或在 shutdown 时已为 0),调用 {@code countDown()} 将计数归零,
|
||
* 使 {@link #shutdown()} 中的 {@code await()} 返回。</p>
|
||
*/
|
||
private final CountDownLatch processingLatch = new CountDownLatch(1);
|
||
|
||
/** 优雅关闭标志位 */
|
||
private volatile boolean shutdownRequested = false;
|
||
|
||
// ──────────────────────────── 轮询入口 ────────────────────────────
|
||
|
||
/**
|
||
* 定时轮询方法,按 {@code polling.fixedDelay} 间隔执行。
|
||
*/
|
||
@Scheduled(fixedDelayString = "${polling.fixedDelay:10000}")
|
||
public void pollAndProcess() {
|
||
// 1. 检查关闭请求
|
||
if (shutdownRequested) {
|
||
log.debug("轮询已请求关闭,跳过本次轮询");
|
||
return;
|
||
}
|
||
|
||
// log.debug("开始轮询未读问题,batchSize={}", batchSize);
|
||
|
||
// 2. 拉取未处理问题
|
||
List<QnA> unreadQuestions = qnAMapper.selectUnreadForProcessing(batchSize);
|
||
if (unreadQuestions == null || unreadQuestions.isEmpty()) {
|
||
// log.debug("本次轮询无新问题");
|
||
return;
|
||
}
|
||
|
||
// 3. 收集 helpId 并原子性置为 state=1
|
||
List<Integer> helpIds = unreadQuestions.stream()
|
||
.map(QnA::getHelpId)
|
||
.toList();
|
||
String idsStr = helpIds.stream()
|
||
.map(String::valueOf)
|
||
.collect(Collectors.joining(","));
|
||
|
||
boolean updated = qnaService.setByIds(idsStr, 1);
|
||
if (!updated) {
|
||
log.warn("批量设置 state=1 失败,跳过本次处理, ids={}", idsStr);
|
||
return;
|
||
}
|
||
// log.info("已领取 {} 条问题(state→1), ids={}", helpIds.size(), idsStr);
|
||
|
||
// 4. 逐条串行处理
|
||
for (QnA question : unreadQuestions) {
|
||
if (shutdownRequested) {
|
||
log.info("收到关闭请求,停止处理剩余问题");
|
||
break;
|
||
}
|
||
|
||
// 增加在途计数
|
||
inFlightCount.incrementAndGet();
|
||
try {
|
||
processQuestion(question);
|
||
} catch (Exception e) {
|
||
log.error("处理问题异常, helpId={}", question.getHelpId(), e);
|
||
// 保持 state=1(处理中),不重置为 0,避免无限重试同一条失败记录
|
||
question.setState(1);
|
||
qnaService.updateById(question);
|
||
} finally {
|
||
// 减少在途计数;若所有在途任务完成且已请求关闭,则释放 processingLatch
|
||
if (inFlightCount.decrementAndGet() == 0 && shutdownRequested) {
|
||
processingLatch.countDown();
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/** 需要从 MySQL 获取答案的已匹配状态集合 */
|
||
private static final Set<Integer> STATES_NEED_FETCH_ANSWER = Set.of(4, 6);
|
||
|
||
// ──────────────────────────── 单条处理 ────────────────────────────
|
||
|
||
/**
|
||
* 处理单个已领取问题(state=1):调用 RAG 生成答案 → 持久化。
|
||
*
|
||
* <ul>
|
||
* <li>若 RAG 返回已有匹配(helpId 非空)→ 复制匹配状态/答案</li>
|
||
* <li>否则按置信度路由:≥ 0.9 → state=4(已回答),< 0.9 → state=2(待人工编辑)</li>
|
||
* </ul>
|
||
*
|
||
* @param question 已领取的待处理问题
|
||
*/
|
||
private void processQuestion(QnA question) {
|
||
final int helpId = question.getHelpId();
|
||
final String questionText = question.getQuestion();
|
||
final String helpTypeId = question.getHelpTypeId();
|
||
|
||
log.info("开始处理问题 helpId={}, question={}", helpId,
|
||
questionText != null
|
||
? questionText.substring(0, Math.min(80, questionText.length()))
|
||
: "(null)");
|
||
|
||
RagQueryResponse queryResponse;
|
||
try {
|
||
RagQueryRequest request = new RagQueryRequest();
|
||
request.setQuestion(questionText);
|
||
request.setHelpTypeId(helpTypeId);
|
||
// 重复问题拦截:检查 state=3(粗口)、4(已回答)、5(无效)的历史记录
|
||
List<QnA> duplicateRecords = qnAMapper.getDuplicateCheckRecords(question.getUserId(), helpTypeId);
|
||
if (questionText != null && duplicateRecords != null) {
|
||
for (QnA history : duplicateRecords) {
|
||
if (history.getQuestion() != null
|
||
&& history.getQuestion().trim().equals(questionText.trim())) {
|
||
log.info("检测到重复问题, helpId={}, 重复来源 help_id={}, state={}, 置 state=5 跳过处理",
|
||
helpId, history.getHelpId(), history.getState());
|
||
question.setState(5);
|
||
qnaService.updateById(question);
|
||
return;
|
||
}
|
||
}
|
||
}
|
||
|
||
// 查询用户5条已回答的历史问答作为 RAG 上下文(仅 state=4)
|
||
List<QnA> historyRecords = qnAMapper.getLatestQA(question.getUserId(), helpTypeId);
|
||
if (historyRecords != null && !historyRecords.isEmpty()) {
|
||
List<String> historyQAList = historyRecords.stream()
|
||
.map(q -> "User: " + q.getQuestion() + "\nAssistant: " + q.getAnswer())
|
||
.toList();
|
||
request.setHistoryQa(historyQAList);
|
||
}
|
||
queryResponse = ragClientService.query(request);
|
||
} catch (IOException e) {
|
||
log.error("RAG 生成调用失败, helpId={}", helpId, e);
|
||
return;
|
||
}
|
||
|
||
if (queryResponse == null || !queryResponse.isSuccess()) {
|
||
log.warn("RAG 生成失败, helpId={}, error={}", helpId,
|
||
queryResponse != null ? queryResponse.getErrorMessage() : "null response");
|
||
return;
|
||
}
|
||
|
||
if (queryResponse.getHelpId() != null) {
|
||
handleQVMatched(question, queryResponse);
|
||
return;
|
||
}
|
||
|
||
double confidence = queryResponse.getConfidence() != null ? queryResponse.getConfidence() : 0.0;
|
||
String answer = queryResponse.getAnswer();
|
||
|
||
int newState;
|
||
if (confidence >= 0.9) {
|
||
newState = 4; // 已回答
|
||
log.info("RAG 高置信度回答, helpId={}, confidence={}", helpId, String.format("%.4f", confidence));
|
||
} else {
|
||
newState = 2; // 待人工编辑
|
||
log.info("RAG 低置信度回答, helpId={}, confidence={}, 转人工", helpId, String.format("%.4f", confidence));
|
||
}
|
||
|
||
int confidenceInt = (int) Math.round(confidence * 10000);
|
||
saveResult(question, answer, newState, confidenceInt);
|
||
}
|
||
|
||
// ──────────────────── 内部辅助方法 ────────────────────
|
||
|
||
/**
|
||
* QV匹配处理
|
||
*/
|
||
private void handleQVMatched(QnA question, RagQueryResponse response){
|
||
Integer helpId = question.getHelpId();
|
||
Integer matchedId = response.getHelpId();
|
||
int matchedState = response.getHelpState();
|
||
|
||
log.info("相似度匹配成功, helpId={}, matchedHelpId={}, matchedState={}, score={}",
|
||
helpId, matchedId, matchedState, String.format("%.4f", response.getConfidence()));
|
||
|
||
if(STATES_NEED_FETCH_ANSWER.contains(matchedState)) { // 匹配状态 4/6:从 MySQL 获取答案
|
||
QnA record = qnaService.getById(matchedId);
|
||
|
||
if (record == null) {
|
||
log.warn("无法从 MySQL 获取匹配问题的答案, matchedId={}", matchedId);
|
||
return;
|
||
}
|
||
|
||
question.setAnswer(record.getAnswer());
|
||
question.setState(4);
|
||
}
|
||
else{
|
||
question.setState(matchedState);
|
||
}
|
||
question.setConfidence((int) Math.round(response.getConfidence() * 10000));
|
||
qnaService.updateById(question);
|
||
}
|
||
/**
|
||
* 持久化处理结果(答案 + 状态),answer_time 由 {@link QnAServiceImpl#updateOrSave} 自动设置。
|
||
*/
|
||
private void saveResult(QnA question, String answer, int state, int confidence) {
|
||
QnAUpdateBO bo = new QnAUpdateBO();
|
||
bo.setHelpId(question.getHelpId());
|
||
bo.setQuestion(question.getQuestion());
|
||
bo.setHelpTypeId(question.getHelpTypeId());
|
||
// 将连续换行合并为单换行,避免存入数据库的格式问题
|
||
String cleanAnswer = answer.replace("\r\n", "\n").replaceAll("\n{2,}", "\n");
|
||
bo.setAnswer(cleanAnswer);
|
||
bo.setState(state);
|
||
bo.setConfidence(confidence);
|
||
|
||
boolean saved = qnaService.updateOrSave(bo);
|
||
if (!saved) {
|
||
log.error("持久化处理结果失败, helpId={}, state={}", question.getHelpId(), state);
|
||
return;
|
||
}
|
||
|
||
log.info("已保存处理结果, helpId={}, state={}", question.getHelpId(), state);
|
||
}
|
||
|
||
// ──────────────────────────── 优雅关闭 ────────────────────────────
|
||
|
||
/**
|
||
* Spring 容器关闭时触发,设置关闭标志并等待所有在途问题处理完毕。
|
||
*
|
||
* <p>执行流程:</p>
|
||
* <ol>
|
||
* <li>设置 {@code shutdownRequested = true},阻止后续轮询和剩余问题处理</li>
|
||
* <li>若当前无在途任务({@code inFlightCount == 0}),立即释放 latch</li>
|
||
* <li>否则等待最后一个在途任务完成后释放 latch</li>
|
||
* </ol>
|
||
*/
|
||
@PreDestroy
|
||
public void shutdown() {
|
||
log.info("QuestionPollingService 收到关闭信号,等待在途任务完成...");
|
||
shutdownRequested = true;
|
||
|
||
// 若当前无在途任务,直接释放 latch 避免永久阻塞
|
||
if (inFlightCount.get() == 0) {
|
||
processingLatch.countDown();
|
||
}
|
||
|
||
try {
|
||
boolean completed = processingLatch.await(60, TimeUnit.SECONDS);
|
||
if (completed) {
|
||
log.info("QuestionPollingService 已优雅关闭,所有在途任务已完成");
|
||
} else {
|
||
log.warn("QuestionPollingService 关闭超时(60s),可能存在未完成的在途任务");
|
||
}
|
||
} catch (InterruptedException e) {
|
||
Thread.currentThread().interrupt();
|
||
log.warn("等待关闭被中断", e);
|
||
}
|
||
}
|
||
}
|