Spring AI Alibaba实战:5分钟搞定通义千问流式API接入(附完整代码)
Spring AI Alibaba实战5分钟搞定通义千问流式API接入附完整代码当Java开发者需要快速验证大模型能力时往往被复杂的API文档和繁琐的配置流程劝退。今天我们就用最精简的代码在Spring Boot项目中实现通义千问的流式对话功能——从零开始到完整运行整个过程不超过5分钟。1. 环境准备与密钥配置在开始编码前我们需要确保基础环境就绪。不同于传统Spring Boot项目这里需要特别注意三个关键点JDK版本必须使用JDK 17或更高版本推荐Amazon Corretto 17Spring Boot版本要求3.3.x以上当前稳定版为3.3.4阿里云API密钥前往阿里云百炼控制台开通服务并获取密钥将获取的API密钥配置到环境变量中export AI_DASHSCOPE_API_KEY您的实际密钥或者在application.properties中直接写入spring.ai.dashscope.api-keysk-您的实际密钥提示生产环境建议使用Vault或KMS等密钥管理服务避免硬编码敏感信息2. 项目依赖配置由于Spring AI Alibaba尚处于快速迭代阶段需要在pom.xml中添加特殊仓库配置repositories repository idspring-milestones/id urlhttps://repo.spring.io/milestone/url /repository repository idspring-snapshots/id urlhttps://repo.spring.io/snapshot/url snapshotsenabledtrue/enabled/snapshots /repository /repositories核心依赖项配置如下dependencies !-- Spring AI Alibaba 核心组件 -- dependency groupIdcom.alibaba.cloud.ai/groupId artifactIdspring-ai-alibaba-starter/artifactId version1.0.0-M2/version /dependency !-- WebFlux 响应式支持 -- dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-webflux/artifactId /dependency /dependencies3. 流式API控制器实现创建ChatController.java文件实现支持流式输出的对话接口RestController RequestMapping(/api/chat) public class ChatController { private final ChatClient chatClient; Autowired public ChatController(ChatClient.Builder builder) { this.chatClient builder.build(); } GetMapping(produces MediaType.TEXT_EVENT_STREAM_VALUE) public FluxString streamChat(RequestParam String message) { return chatClient.prompt() .user(u - u.text(message)) .stream() .content(); } }这段代码实现了几个关键功能通过ChatClient.Builder自动装配聊天客户端使用MediaType.TEXT_EVENT_STREAM_VALUE声明流式输出通过stream().content()实现实时数据流返回4. 进阶功能扩展基础功能实现后我们可以通过以下方式增强接口能力4.1 添加Prompt模板在resources/templates目录下创建chat.st模板文件user: 请用专业但易懂的方式回答以下问题{question}修改控制器代码使用模板Value(classpath:templates/chat.st) private Resource templateResource; GetMapping(/expert) public FluxString expertAnswer(RequestParam String question) { PromptTemplate template new PromptTemplate(templateResource); Prompt prompt template.create(Map.of(question, question)); return chatClient.prompt(prompt).stream().content(); }4.2 流式性能优化对于高并发场景建议配置连接池参数spring.ai.dashscope.connect-timeout5000 spring.ai.dashscope.read-timeout30000 spring.ai.dashscope.max-connections504.3 异常处理机制增强控制器的健壮性ExceptionHandler(DashScopeException.class) public ResponseEntityString handleAiError(DashScopeException ex) { return ResponseEntity.status(502) .body(AI服务异常: ex.getError().getMessage()); }5. 测试与验证启动应用后可以通过以下方式测试接口cURL测试命令curl -N http://localhost:8080/api/chat?message如何学习Spring框架前端对接示例使用EventSourceconst eventSource new EventSource(/api/chat?message你好); eventSource.onmessage (e) { console.log(收到数据:, e.data); // 实时渲染到页面... };响应示例data: Spring框架学习建议... data: 1. 从官方文档开始... data: 2. 实践核心模块...在实际项目中我发现流式接口对网络稳定性要求较高。当遇到中断时最佳实践是客户端保留已接收内容自动重连时携带最后收到的片段ID服务端支持断点续传逻辑