提供一个日志管理模块的服务,这样嵌入代码比较小
@Slf4j
@EnableScheduling
@Service
public class QueryLogManager {
@Autowired
RedisService redisService;
@Autowired
SrClient srClient;
private List<String> queryDetails = new CopyOnWriteArrayList<>();
//十秒钟刷新一次数据
@Scheduled(fixedDelay = 10000)
public void sendMessageToSR() {
List<String> aiContentList = getQueryMetricsAndClear();
for (AiContentStats aiContent : aiContentList) {
String queryId = String.valueOf(aiContent.getQueryId());
int step = redisService.getJedis().exists(queryId) ? MathUtils.getIntegerByStr(redisService.getJedis().get(queryId)) : 1;
if (step == 1) {
//第一次只有跟ai模型交互,则直接添加数据
log.info("第一次日志请求:{}", aiContent);
srClient.addAiContent(aiContent, step);
}else if( step == 2){
//第二次只有跟ai模型交互,则直接添加数据, 因为不直接支持update语法,需要通过step和queryId作为唯一主键进行合并
log.info("第二次日志请求:{}", aiContent);
srClient.updateAiContent(aiContent, step -1 );
}else {
//如果超过2的,说明多次查询,则复制原来的数据进行
log.info("第三次日志请求:{}", aiContent);
srClient.updateAiContent(aiContent, step);
}
step = step +1;
}
}
public void addLog(String queryDetail) {
queryDetails.add(queryDetail);
}
public List<String> getQueryMetricsAndClear() {
List<String> tmpQueryDetail = new ArrayList<>();
tmpQueryDetail.addAll(queryDetails);
queryDetails.clear();
return tmpQueryDetail;
}
}