You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot后端分批推送第三方API数据至前端的可行方案咨询

可行方案建议:分步推送第三方API数据到前端

一、WebSocket方案(推荐,灵活支持双向通信)

你的场景完全适合用WebSocket,它支持后端主动、多次向前端推送数据,完美匹配「拿到首个数据源就返回,持续推送直至全部完成」的需求。

实现核心要点

  1. 引入依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
  1. 配置WebSocket端点
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(dataPushHandler(), "/data-push")
                .setAllowedOrigins("*"); // 生产环境替换为前端域名
    }

    @Bean
    public WebSocketHandler dataPushHandler() {
        return new DataPushHandler();
    }
}
  1. 实现消息推送逻辑
public class DataPushHandler extends TextWebSocketHandler {
    @Autowired
    private ThirdPartyApiService apiService;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 并行异步调用所有第三方API,拿到结果就推送
        CompletableFuture.allOf(
                CompletableFuture.runAsync(() -> pushSingleApiData(session, "api1")),
                CompletableFuture.runAsync(() -> pushSingleApiData(session, "api2")),
                CompletableFuture.runAsync(() -> pushSingleApiData(session, "api3"))
        ).thenRun(() -> {
            try {
                session.sendMessage(new TextMessage("{\"type\":\"finish\",\"msg\":\"所有数据推送完成\"}"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    private void pushSingleApiData(WebSocketSession session, String apiName) {
        try {
            String apiResponse = apiService.callThirdPartyApi(apiName);
            session.sendMessage(new TextMessage("{\"type\":\"data\",\"source\":\"" + apiName + "\",\"content\":" + apiResponse + "}"));
        } catch (Exception e) {
            try {
                session.sendMessage(new TextMessage("{\"type\":\"error\",\"source\":\"" + apiName + "\",\"msg\":\"" + e.getMessage() + "\"}"));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
  1. 前端接收处理
const socket = new WebSocket('ws://localhost:8080/data-push');
socket.onmessage = function(event) {
    const msg = JSON.parse(event.data);
    switch(msg.type) {
        case 'data':
            console.log(`收到${msg.source}数据:`, msg.content);
            // 更新页面展示逻辑
            break;
        case 'error':
            console.error(`${msg.source}调用失败:`, msg.msg);
            break;
        case 'finish':
            console.log(msg.msg);
            socket.close();
            break;
    }
};

二、Server-Sent Events(SSE)方案(轻量单向推送)

如果你的场景只需要后端向前端单向推送数据,SSE是更轻量的选择——基于HTTP协议,无需额外协议支持,实现更简单。

实现核心要点

  1. 编写SSE控制器
@RestController
@RequestMapping("/sse")
public class SseDataController {
    @Autowired
    private ThirdPartyApiService apiService;

    @GetMapping("/data-stream")
    public SseEmitter streamData() {
        SseEmitter emitter = new SseEmitter(Long.MAX_VALUE);
        // 并行调用第三方API,逐个推送结果
        CompletableFuture.allOf(
                CompletableFuture.runAsync(() -> sendSingleApiData(emitter, "api1")),
                CompletableFuture.runAsync(() -> sendSingleApiData(emitter, "api2")),
                CompletableFuture.runAsync(() -> sendSingleApiData(emitter, "api3"))
        ).thenRun(() -> {
            try {
                emitter.send(SseEmitter.event().name("finish").data("所有数据推送完成"));
                emitter.complete();
            } catch (IOException e) {
                emitter.completeWithError(e);
            }
        });
        return emitter;
    }

    private void sendSingleApiData(SseEmitter emitter, String apiName) {
        try {
            String apiResponse = apiService.callThirdPartyApi(apiName);
            emitter.send(SseEmitter.event().name("data").data(
                    Map.of("source", apiName, "content", apiResponse)
            ));
        } catch (Exception e) {
            try {
                emitter.send(SseEmitter.event().name("error").data(
                        Map.of("source", apiName, "msg", e.getMessage())
                ));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
  1. 前端接收处理
const eventSource = new EventSource('http://localhost:8080/sse/data-stream');
eventSource.addEventListener('data', function(event) {
    const data = JSON.parse(event.data);
    console.log(`收到${data.source}数据:`, data.content);
    // 更新页面展示逻辑
});
eventSource.addEventListener('error', function(event) {
    const error = JSON.parse(event.data);
    console.error(`${error.source}调用失败:`, error.msg);
});
eventSource.addEventListener('finish', function(event) {
    console.log(event.data);
    eventSource.close();
});

三、方案选择建议

  • WebSocket:适合需要双向交互的场景(比如前端要给后端发控制指令),兼容性覆盖所有现代浏览器。
  • SSE:仅支持单向推送,代码更简洁,无需额外协议适配,完全满足你当前「后端推数据到前端」的核心需求。

两种方案都能实现「拿到首个数据就推送,无需等待全部API完成」的目标,可根据业务后续扩展需求选择。

内容的提问来源于stack exchange,提问作者anonymous-java-dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 01:08:33