JAVA并发调用接口

发布时间 2024-01-09 14:49:45作者: 唐胜伟
package com.cpiaoju.sdk.controller;

import com.alibaba.fastjson.JSONObject;
import com.cpiaoju.sdk.api.LxskApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@RestController
public class SignController {
    private static final String LXSK_URL = "http://172.16.88.54:13001/cpiaoju-bss-sign/sign";

    @PostMapping(value = "/sign")
    @ResponseBody
    public void getDataByTypeByDy() {
        // 创建线程池
        ExecutorService executorService = Executors.newFixedThreadPool(3);

        // 创建CompletableFuture列表,每个CompletableFuture代表一个异步签章请求
        CompletableFuture<String> futureA = CompletableFuture.supplyAsync(() -> signDocument("AAA.pdf"));
        CompletableFuture<String> futureB = CompletableFuture.supplyAsync(() -> signDocument("AAA.pdf"));
        CompletableFuture<String> futureC = CompletableFuture.supplyAsync(() -> signDocument("AAA.pdf"));

        // 等待所有异步请求完成,并获取结果
        CompletableFuture<Void> allOf = CompletableFuture.allOf(futureA, futureB, futureC);
        allOf.join();

        try {
            // 获取异步请求的结果
            String urlA = futureA.get();
            String urlB = futureB.get();
            String urlC = futureC.get();

            // 在这里你可以使用获取到的URL值进行后续操作
            System.out.println("URL from task A: " + urlA);
            System.out.println("URL from task B: " + urlB);
            System.out.println("URL from task C: " + urlC);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭线程池
            executorService.shutdown();
        }
    }

    private String signDocument(String pdfFileName) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("pdfUrl", "https://-beijing.aliyuncs.com/test/" + pdfFileName);
        jsonObject.put("customerType", "2");
        jsonObject.put("keyWord", ":");

        // 接口调用
        JSONObject response = LxskApi.post(LXSK_URL, jsonObject);

        // 从响应中提取URL值
        if ("10000".equals(response.getString("code"))) {
            return response.getJSONObject("data").getString("url");
        } else {
            throw new RuntimeException("Failed to sign document. Response: " + response.toJSONString());
        }
    }
}