赵建洲 發表於 2026-3-31 14:01:00

Spring AI实战:10分钟接入OpenAI实现流式对话

<h2>前言</h2>
<p>Spring AI 是 Spring 官方推出的 AI 集成框架,让 Java 开发者能用熟悉的 Spring 风格快速接入各大 AI 模型。本文带你 10 分钟完成 OpenAI 接入,并实现流式对话效果。</p>
<h2>一、环境准备</h2>
<pre><code>&lt;dependency&gt;
    &lt;groupId&gt;org.springframework.ai&lt;/groupId&gt;
    &lt;artifactId&gt;spring-ai-openai-spring-boot-starter&lt;/artifactId&gt;
    &lt;version&gt;1.0.0-M6&lt;/version&gt;
&lt;/dependency&gt;</code></pre>
<h2>二、配置 API Key</h2>
<pre><code># application.yml
spring:
ai:
    openai:
      api-key: your-api-key-here
      chat:
      options:
          model: gpt-4o-mini
          temperature: 0.7</code></pre>
<h2>三、普通对话</h2>
<pre><code>@RestController
@RequestMapping("/ai")
public class ChatController {

    private final ChatClient chatClient;

    public ChatController(ChatClient.Builder builder) {
      this.chatClient = builder
            .defaultSystem("你是一个专业的Java技术顾问,回答简洁专业。")
            .build();
    }

    @GetMapping("/chat")
    public String chat(@RequestParam String message) {
      return chatClient.prompt()
            .user(message)
            .call()
            .content();
    }
}</code></pre>
<h2>四、流式对话(打字机效果)</h2>
<pre><code>@GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux&lt;String&gt; stream(@RequestParam String message) {
    return chatClient.prompt()
      .user(message)
      .stream()
      .content();
}

// 前端接收流式响应
const eventSource = new EventSource("/ai/stream?message=介绍Spring AI");
eventSource.onmessage = (event) =&gt; {
    document.getElementById("output").innerHTML += event.data;
};
eventSource.onerror = () =&gt; eventSource.close();</code></pre>
<h2>五、多轮对话(带记忆)</h2>
<pre><code>@RestController
public class MemoryChatController {

    private final ChatClient chatClient;

    public MemoryChatController(ChatClient.Builder builder, ChatMemory chatMemory) {
      this.chatClient = builder
            .defaultAdvisors(new MessageChatMemoryAdvisor(chatMemory))
            .build();
    }

    @GetMapping("/memory-chat")
    public String memoryChat(
            @RequestParam String message,
            @RequestParam(defaultValue = "default") String sessionId) {
      return chatClient.prompt()
            .user(message)
            .advisors(a -&gt; a.param(CHAT_MEMORY_CONVERSATION_ID_KEY, sessionId))
            .call()
            .content();
    }
}</code></pre>
<h2>六、结构化输出</h2>
<pre><code>record MovieRecommendation(String title, String director, int year, String reason) {}

@GetMapping("/recommend")
public MovieRecommendation recommend(@RequestParam String genre) {
    return chatClient.prompt()
      .user("推荐一部" + genre + "类型的电影,用JSON格式返回")
      .call()
      .entity(MovieRecommendation.class);
}</code></pre>
<h2>总结</h2>
<p>Spring AI 让 Java 开发者以最小的学习成本接入 AI 能力。核心优势:统一抽象(一套 API 支持 OpenAI、Azure、Ollama 等多个模型);Spring 生态无缝集成;流式输出、多轮对话、结构化输出开箱即用。</p>
<p>觉得有帮助请点赞收藏!有问题欢迎评论区交流 🚀</p>

</div>
<div id="MySignature" role="contentinfo">
   

---

📌 **如果觉得文章对你有帮助,欢迎点赞👍收藏⭐!**

💬 有问题或建议?欢迎在评论区留言讨论~

🔗 更多技术干货请关注作者:弥烟袅绕

📚 本文地址:https://www.cnblogs.com/czlws/p/19801096/spring-ai-openai-java-streaming-chat<br><br>
来源:https://www.cnblogs.com/czlws/p/19801096/spring-ai-openai-java-streaming-chat
頁: [1]
查看完整版本: Spring AI实战:10分钟接入OpenAI实现流式对话