做任务得得q币的网站,电商网址,做彩妆发哪个网站浏览量高,开封市网站开发公司在当今 AI 时代#xff0c;大模型 API#xff08;如 OpenAI 的 GPT、百度的文心一言、阿里云的通义千问#xff09;已成为开发者集成智能功能的核心工具。Spring Boot 作为现代 Java 开发的首选框架#xff0c;其内置的 WebClient#xff08;基于 Reactor 的非阻塞 HTTP 客…在当今 AI 时代大模型 API如 OpenAI 的 GPT、百度的文心一言、阿里云的通义千问已成为开发者集成智能功能的核心工具。Spring Boot作为现代 Java 开发的首选框架其内置的WebClient基于 Reactor 的非阻塞 HTTP 客户端是调用 REST API 的高效、灵活的方式。本文将详细介绍如何使用 Spring Boot 的WebClient来调用主流大模型 API帮助你快速上手。一、为什么选择 WebClient特性RestTemplateWebClient同步/异步同步阻塞异步非阻塞响应式线程模型每个请求占用一个线程事件驱动高并发流式处理不支持支持响应流Streaming错误处理复杂链式调用简洁Spring 生态旧版Spring 5 开始弃用Spring 5 推荐✅推荐使用WebClient它更符合现代微服务架构的需求能显著提升系统吞吐量。二、项目准备1. 创建 Spring Boot 项目使用 Spring Initializr 创建项目选择以下依赖Spring Webflux自动包含WebClientLombok可选简化 DTO 代码2.pom.xml依赖dependencies !-- Spring WebFlux (包含 WebClient) -- dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-webflux/artifactId /dependency !-- JSON 处理Jackson 自动包含 -- !-- 可选Lombok 简化 DTO -- dependency groupIdorg.projectlombok/groupId artifactIdlombok/artifactId scopeprovided/scope /dependency /dependencies3. 读取 API 密钥推荐使用环境变量在application.yml中配置密钥切勿硬编码api: openai: key: ${OPENAI_API_KEY} # 从环境变量读取 wenxin: api-key: ${WENXIN_API_KEY} secret-key: ${WENXIN_SECRET_KEY} tongyi: key: ${TONGYI_API_KEY}在服务类中注入Service public class ApiConfig { Value(${api.openai.key}) private String openaiApiKey; Value(${api.wenxin.api-key}) private String wenxinApiKey; Value(${api.wenxin.secret-key}) private String wenxinSecretKey; Value(${api.tongyi.key}) private String tongyiApiKey; }三、WebClient 基础配置创建一个WebClientConfig类封装通用配置import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.reactive.ReactorClientHttpConnector; import org.springframework.web.reactive.function.client.WebClient; import reactor.netty.http.client.HttpClient; Configuration public class WebClientConfig { // 可选配置超时、重试、连接池 Bean public WebClient webClient() { HttpClient httpClient HttpClient.create() .responseTimeout(java.time.Duration.ofSeconds(30)); // 请求超时 30 秒 return WebClient.builder() .clientConnector(new ReactorClientHttpConnector(httpClient)) .build(); } }提示生产环境中应配置重试策略如Retry、日志跟踪等。四、调用 OpenAI API1. OpenAI API 简介端点https://api.openai.com/v1/chat/completions必需头Authorization: Bearer API_KEY请求体JSON 格式包含model、messages等字段。官方文档OpenAI API Reference2. DTO 定义import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; // 请求体 Data NoArgsConstructor AllArgsConstructor class OpenAiRequest { private String model; // 模型名如 gpt-3.5-turbo private ListMessage messages; } Data NoArgsConstructor AllArgsConstructor class Message { private String role; // user, assistant, system private String content; } // 响应体简化版仅展示关键字段 Data class OpenAiResponse { private ListChoice choices; Data static class Choice { private Message message; } }3. 服务实现import org.springframework.beans.factory.annotation.Value; import org.springframework.http.MediaType; import org.springframework.stereotype.Service; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; Service public class OpenAiService { private final WebClient webClient; private final String apiKey; public OpenAiService(WebClient.Builder webClientBuilder, Value(${api.openai.key}) String apiKey) { this.webClient webClientBuilder .baseUrl(https://api.openai.com/v1) .defaultHeader(Authorization, Bearer apiKey) .build(); this.apiKey apiKey; } public MonoString chat(String prompt) { // 构造请求体 OpenAiRequest request new OpenAiRequest( gpt-3.5-turbo, List.of(new Message(user, prompt)) ); // 发送请求 return webClient.post() .uri(/chat/completions) .contentType(MediaType.APPLICATION_JSON) .bodyValue(request) .retrieve() .bodyToMono(OpenAiResponse.class) .map(response - response.getChoices().get(0).getMessage().getContent()); } }4. 使用示例Controllerimport org.springframework.web.bind.annotation.*; import reactor.core.publisher.Mono; RestController RequestMapping(/ai) public class AiController { private final OpenAiService openAiService; public AiController(OpenAiService openAiService) { this.openAiService openAiService; } GetMapping(/ask) public MonoString askOpenAi(RequestParam String question) { return openAiService.chat(question); } }测试发送 GET 请求http://localhost:8080/ai/ask?question你好将返回 GPT 的回答。五、调用文心一言 API1. 文心一言 API 简介获取访问令牌Access Token首先需调用 OAuth 2.0 获取access_token。端点https://aip.baidubce.com/oauth/2.0/token参数grant_typeclient_credentialsclient_idAPI_KEYclient_secretSECRET_KEY聊天接口端点https://aip.baidubce.com/rpc/2.0/ai/custom/v1/wenxinworkshop/chat/completions?access_tokenTOKEN请求体格式类似 OpenAI但字段名不同。注意文心一言需在百度智能云控制台创建应用并获取密钥。2. DTO 定义// 访问令牌响应 Data class WenxinTokenResponse { private String access_token; private String expires_in; } // 文心一言请求体 Data NoArgsConstructor AllArgsConstructor class WenxinRequest { private String model eb-instant; // 模型名如 eb-instant、ernie-3.5-4k-0205 private ListMessage messages; } // 文心一言响应体 Data class WenxinResponse { private ListChoice result; Data static class Choice { private String content; } }3. 服务实现import org.springframework.beans.factory.annotation.Value; import org.springframework.http.MediaType; import org.springframework.stereotype.Service; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; Service public class WenxinService { private final WebClient webClient; private final String apiKey; private final String secretKey; public WenxinService(WebClient.Builder webClientBuilder, Value(${api.wenxin.api-key}) String apiKey, Value(${api.wenxin.secret-key}) String secretKey) { this.webClient webClientBuilder.build(); this.apiKey apiKey; this.secretKey secretKey; } // Step 1: 获取 Access Token private MonoString getAccessToken() { return webClient.post() .uri(https://aip.baidubce.com/oauth/2.0/token) .queryParam(grant_type, client_credentials) .queryParam(client_id, apiKey) .queryParam(client_secret, secretKey) .retrieve() .bodyToMono(WenxinTokenResponse.class) .map(WenxinTokenResponse::getAccess_token); } // Step 2: 调用聊天接口 public MonoString chat(String prompt) { return getAccessToken().flatMap(accessToken - { WenxinRequest request new WenxinRequest( List.of(new Message(user, prompt)) ); return webClient.post() .uri(https://aip.baidubce.com/rpc/2.0/ai/custom/v1/wenxinworkshop/chat/completions) .queryParam(access_token, accessToken) .contentType(MediaType.APPLICATION_JSON) .bodyValue(request) .retrieve() .bodyToMono(WenxinResponse.class) .map(resp - resp.getResult().get(0).getContent()); }); } }4. Controller 使用RestController RequestMapping(/ai) public class AiController { private final WenxinService wenxinService; public AiController(WenxinService wenxinService) { this.wenxinService wenxinService; } GetMapping(/wenxin) public MonoString askWenxin(RequestParam String question) { return wenxinService.chat(question); } }六、调用通义千问 API1. 通义千问 API 简介端点https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation必需头Authorization: Bearer API_KEY模型dall-e-xl图像或qwen-plus文本官方文档通义千问 API 文档注意通义千问由阿里云提供需在阿里云控制台获取 API 密钥。2. DTO 定义// 请求体 Data NoArgsConstructor AllArgsConstructor class TongyiRequest { private String model qwen-long; // 模型名 private ListMessage input new ArrayList(); private Parameters parameters new Parameters(); Data NoArgsConstructor AllArgsConstructor static class Parameters { private float temperature 0.7f; // 随机性 private int max_tokens 800; // 最多生成 token 数 } } // 响应体 Data class TongyiResponse { private Output output; Data static class Output { private ListText text; Data static class Text { private String content; } } }3. 服务实现import org.springframework.beans.factory.annotation.Value; import org.springframework.http.MediaType; import org.springframework.stereotype.Service; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; Service public class TongyiService { private final WebClient webClient; private final String apiKey; public TongyiService(WebClient.Builder webClientBuilder, Value(${api.tongyi.key}) String apiKey) { this.webClient webClientBuilder .baseUrl(https://dashscope.aliyuncs.com) .defaultHeader(Authorization, Bearer apiKey) .defaultHeader(Content-Type, MediaType.APPLICATION_JSON) .build(); this.apiKey apiKey; } public MonoString chat(String prompt) { TongyiRequest request new TongyiRequest(); request.getInput().add(new Message(user, prompt)); return webClient.post() .uri(/api/v1/services/aigc/text-generation/generation) .bodyValue(request) .retrieve() .bodyToMono(TongyiResponse.class) .map(resp - resp.getOutput().getText().get(0).getContent()); } }4. Controller 使用RestController RequestMapping(/ai) public class AiController { private final TongyiService tongyiService; public AiController(TongyiService tongyiService) { this.tongyiService tongyiService; } GetMapping(/tongyi) public MonoString askTongyi(RequestParam String question) { return tongyiService.chat(question); } }七、错误处理与最佳实践1. 优雅处理 HTTP 错误使用onStatus()捕获 4xx/5xx 错误public MonoString chat(String prompt) { return webClient.post() .uri(/chat/completions) .bodyValue(request) .retrieve() .onStatus(httpStatus - httpStatus.value() 400, clientResponse - { // 读取错误信息 return clientResponse.bodyToMono(String.class) .flatMap(errorBody - Mono.error(new RuntimeException( API 调用失败: httpStatus.getReasonPhrase() , errorBody ))); }) .bodyToMono(OpenAiResponse.class) .map(...); }2. 重要最佳实践实践原因密钥隔离使用环境变量、Vault 或 KMS绝不硬编码在代码中超时设置避免请求长时间挂起如.responseTimeout(Duration.ofSeconds(30))重试机制对 5xx 错误使用Retry如Retry.backoff(3, Duration.ofSeconds(1))流式处理大模型响应可能很长支持流式输出如 OpenAI 的streamtrue日志与监控记录请求参数、响应码、耗时方便排查问题令牌刷新文心一言的access_token有有效期24 小时需定期刷新响应式编程在 Reactive 项目中避免使用.block()直接返回Mono/Flux3. 流式输出示例OpenAIpublic FluxString streamChat(String prompt) { OpenAiRequest request new OpenAiRequest(gpt-3.5-turbo, List.of(new Message(user, prompt))); request.setStream(true); // 开启流式 return webClient.post() .uri(/chat/completions) .bodyValue(request) .accept(MediaType.TEXT_EVENT_STREAM) // SSE 格式 .exchangeToFlux(clientResponse - clientResponse.bodyToFlux(String.class)) .filter(chunk - !chunk.trim().isEmpty()) .map(chunk - chunk.split(data: )[1]) .filter(data - !data.equals([\u200b])) // 过滤心跳 .map(data - { /* 解析 JSON 得到内容 */ }); }八、完整项目结构src ├── main │ ├── java │ │ └── com.example.demo │ │ ├── DemoApplication.java │ │ ├── config │ │ │ └── WebClientConfig.java │ │ ├── controller │ │ │ └── AiController.java │ │ ├── dto │ │ │ ├── OpenAiRequest.java │ │ │ ├── WenxinRequest.java │ │ │ └── TongyiRequest.java │ │ ├── service │ │ │ ├── OpenAiService.java │ │ │ ├── WenxinService.java │ │ │ └── TongyiService.java │ │ └── ApiConfig.java │ └── resources │ └── application.yml九、总结通过本文你掌握了如何配置 Spring Boot 的WebClient作为高性能 HTTP 客户端。三大主流大模型 API 的调用流程OpenAI直接传递Bearer Token。文心一言先获取access_token再带参调用。通义千问使用Bearer方式传递 API 密钥。响应式编程实践使用Mono/Flux处理异步调用避免线程阻塞。生产级考量错误处理、密钥管理、超时重试、流式输出等。下一步建议集成Spring AI官方支持的 AI 框架简化大模型调用。尝试流式输出提升用户体验如实时显示模型思考过程。使用缓存存储重复请求的结果降低 API 调用成本。现在你已经可以轻松将大模型能力集成到自己的 Spring Boot 应用中重要提醒大模型 API 通常需要付费按 token 计费请理性使用并遵守各平台的使用政策。本文示例仅用于学习实际项目中请仔细阅读官方文档获取最新接口规范。