接口响应太慢,原因调用某个http请求响应过慢,导致整个接口过慢

解决方法:异步调用这个方法

创建线程池,异步调用

@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);
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

java坤坤

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值