解决方法:异步调用这个方法
创建线程池,异步调用
@Bean(name = "taskExecutor")
public ThreadPoolTaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5); // Set the core pool size
executor.setMaxPoolSize(10); // Set the maximum pool size
executor.setQueueCapacity(25); // Set the queue capacity
executor.initialize();
return executor;
}
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
public class YourServiceClass {
private RequestUtil requestUtil;
public Map<String, Object> CreatePrivateMemory(String text, String userId) throws JSONException {
if (text == null || text.isEmpty()) {
throw new RuntimeException("记忆内容为空");
}
Map<String, Object> res = new HashMap<>();
String currentTime = TimeUtil.getCurrentTime();
String memoryId = "memory_" + UUID.randomUUID().toString().replace("-", "");
JSONObject otherInfo = new JSONObject();
otherInfo.put("type", "more_memory");
Map<String, Object> requestBodyMap = new HashMap<>();
requestBodyMap.put("memory_id", memoryId);
// 异步调用
CompletableFuture<String> future = requestUtil.getAlgorithmResponse("update_private_memory", userId, null, requestBodyMap);
// 处理异步任务完成后的结果
future.whenComplete((body, throwable) -> {
if (throwable != null) {
// 异步任务失败,记录错误信息
System.err.println("调用算法端失败: " + throwable.getMessage());
} else {
try {
ObjectMapper responseMapper = new ObjectMapper();
AlgorithmResponse<String> response = responseMapper.readValue(body, responseMapper.getTypeFactory().constructParametricType(AlgorithmResponse.class, String.class));
if (!response.getResults().equals("success")) {
System.err.println("失败");
}
} catch (Exception e) {
System.err.println("处理算法端响应失败: " + e.getMessage());
}
}
});
res.put("id", memoryId);
res.put("update_time", currentTime);
return res;
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.JSONObject;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@Component
public class RequestUtil {
@Autowired
private RestTemplate restTemplate;
@Value("${algorithm_url}")
private String algorithmUrl;
@Async("taskExecutor")
public CompletableFuture<String> getAlgorithmResponse(String function, String userId, String sessionId, Map<String, Object> requestBodyMap) throws Exception {
String url = algorithmUrl + "/execute";
String requestId = UUID.randomUUID().toString();
// 添加请求头
HttpHeaders headers = new HttpHeaders();
headers.set("function", function);
headers.set("Content-Type", "application/json");
headers.set("userId", userId);
headers.set("requestId", requestId);
headers.set("sessionId", sessionId);
ObjectMapper requestMapper = new ObjectMapper();
String requestBody = requestMapper.writeValueAsString(requestBodyMap);
HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);
try {
ResponseEntity<String> res = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
String body = res.getBody();
if (body != null) {
JSONObject jsonObject = new JSONObject(body);
boolean success = jsonObject.getBoolean("is_success");
if (!success) {
throw new RuntimeException("调用接口:" + function + "报错:" + jsonObject.getString("err_msg"));
}
}
return CompletableFuture.completedFuture(body);
} catch (Exception e) {
return CompletableFuture.failedFuture(e);
}
}
}