丁如意 發表於 2026-4-12 01:36:00

DeepSeek-V3 + Spring Boot实战:10分钟接入国产大模型API

<h2>一、DeepSeek-V3 简介</h2>
<p>DeepSeek-V3是深度求索推出的最新大语言模型,在代码生成和中文理解上表现优异。其API兼容OpenAI格式,开发者可零成本迁移。本文将手把手演示Spring Boot接入DeepSeek-V3 API。</p>
<h2>二、获取API Key</h2>
<p>1. 访问 platform.deepseek.com 注册账号</p>
<p>2. 进入API Keys页面,点击创建API Key</p>
<p>3. 复制Key(格式:sk-xxxxxxxx)</p>
<p>4. 新用户赠送500万Tokens额度</p>
<h2>三、Spring Boot项目搭建</h2>
<h3>3.1 添加依赖</h3>
<pre><code>&lt;dependencies&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
      &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;com.squareup.okhttp3&lt;/groupId&gt;
      &lt;artifactId&gt;okhttp&lt;/artifactId&gt;
      &lt;version&gt;4.12.0&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;com.alibaba.fastjson2&lt;/groupId&gt;
      &lt;artifactId&gt;fastjson2&lt;/artifactId&gt;
      &lt;version&gt;2.0.47&lt;/version&gt;
    &lt;/dependency&gt;
&lt;/dependencies&gt;</code></pre>
<h3>3.2 配置文件</h3>
<pre><code>deepseek:
api-key: sk-your-api-key-here
base-url: https://api.deepseek.com
model: deepseek-chat
max-tokens: 2048
temperature: 0.7</code></pre>
<h3>3.3 配置类</h3>
<pre><code>@Configuration
@ConfigurationProperties(prefix = "deepseek")
@Data
public class DeepSeekConfig {
    private String apiKey;
    private String baseUrl = "https://api.deepseek.com";
    private String model = "deepseek-chat";
    private int maxTokens = 2048;
    private double temperature = 0.7;

    @Bean
    public OkHttpClient okHttpClient() {
      return new OkHttpClient.Builder()
            .connectTimeout(30, TimeUnit.SECONDS)
            .readTimeout(60, TimeUnit.SECONDS)
            .build();
    }
}</code></pre>
<h2>四、核心服务实现</h2>
<h3>4.1 请求DTO</h3>
<pre><code>@Data
public class ChatRequest {
    private String model;
    private List&lt;Message&gt; messages;
    private int max_tokens;
    private double temperature;

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class Message {
      private String role;
      private String content;
    }

    public static ChatRequest create(String systemPrompt, String userMsg, DeepSeekConfig config) {
      ChatRequest req = new ChatRequest();
      req.setModel(config.getModel());
      req.setMax_tokens(config.getMaxTokens());
      req.setTemperature(config.getTemperature());
      req.setMessages(List.of(
            new Message("system", systemPrompt),
            new Message("user", userMsg)
      ));
      return req;
    }
}</code></pre>
<h3>4.2 DeepSeek服务</h3>
<pre><code>@Service
@Slf4j
public class DeepSeekService {
    @Autowired private DeepSeekConfig config;
    @Autowired private OkHttpClient httpClient;

    public String chat(String systemPrompt, String userMsg) {
      ChatRequest request = ChatRequest.create(systemPrompt, userMsg, config);
      String jsonBody = JSON.toJSONString(request);
      RequestBody body = RequestBody.create(jsonBody,
            MediaType.parse("application/json; charset=utf-8"));
      Request httpRequest = new Request.Builder()
            .url(config.getBaseUrl() + "/v1/chat/completions")
            .addHeader("Authorization", "Bearer " + config.getApiKey())
            .post(body).build();
      try (Response response = httpClient.newCall(httpRequest).execute()) {
            if (!response.isSuccessful()) {
                throw new RuntimeException("API error: " + response.code());
            }
            String respJson = response.body().string();
            JSONObject resp = JSON.parseObject(respJson);
            return resp.getJSONArray("choices")
                .getJSONObject(0).getJSONObject("message").getString("content");
      } catch (IOException e) {
            throw new RuntimeException("API exception", e);
      }
    }
}</code></pre>
<h2>五、流式响应SSE</h2>
<pre><code>@GetMapping(value = "/chat/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter streamChat(@RequestParam String message) {
    SseEmitter emitter = new SseEmitter(120000L);
    ChatRequest request = ChatRequest.create("AI助手", message, config);
    request.setStream(true);
    String jsonBody = JSON.toJSONString(request);
    RequestBody body = RequestBody.create(jsonBody,
      MediaType.parse("application/json; charset=utf-8"));
    Request httpRequest = new Request.Builder()
      .url(config.getBaseUrl() + "/v1/chat/completions")
      .addHeader("Authorization", "Bearer " + config.getApiKey())
      .post(body).build();
    httpClient.newCall(httpRequest).enqueue(new Callback() {
      public void onFailure(Call call, IOException e) { emitter.completeWithError(e); }
      public void onResponse(Call call, Response response) {
            try (ResponseBody rb = response.body()) {
                BufferedReader reader = new BufferedReader(
                  new InputStreamReader(rb.byteStream(), StandardCharsets.UTF_8));
                String line;
                while ((line = reader.readLine()) != null) {
                  if (line.startsWith("data: ") &amp;&amp; !line.contains("")) {
                        JSONObject json = JSON.parseObject(line.substring(6));
                        String content = json.getJSONArray("choices")
                            .getJSONObject(0).getJSONObject("delta").getString("content");
                        if (content != null) emitter.send(SseEmitter.event().data(content));
                  }
                }
                emitter.complete();
            } catch (Exception e) { emitter.completeWithError(e); }
      }
    });
    return emitter;
}</code></pre>
<h2>六、Controller</h2>
<pre><code>@RestController
@RequestMapping("/api/deepseek")
public class DeepSeekController {
    @Autowired private DeepSeekService deepSeekService;

    @PostMapping("/chat")
    public Map&lt;String, String&gt; chat(@RequestBody Map&lt;String, String&gt; params) {
      String msg = params.get("message");
      String sys = params.getOrDefault("systemPrompt", "你是AI助手");
      String reply = deepSeekService.chat(sys, msg);
      return Map.of("reply", reply, "model", "deepseek-chat");
    }

    @GetMapping("/chat/stream")
    public SseEmitter streamChat(@RequestParam String message) {
      return deepSeekService.streamChat(message);
    }
}</code></pre>
<h2>七、测试</h2>
<pre><code>curl -X POST http://localhost:8080/api/deepseek/chat -H "Content-Type: application/json" -d "{"message":"用Java写单例","systemPrompt":"Java专家"}"

# 返回: {"reply":"以下是线程安全单例...","model":"deepseek-chat"}

# 流式
curl -N http://localhost:8080/api/deepseek/chat/stream?message=Spring%20Boot</code></pre>
<h2>八、最佳实践</h2>
<ol>
<li><strong>API Key安全</strong>:用环境变量,勿硬编码</li>
<li><strong>限流</strong>:加Semaphore限制并发</li>
<li><strong>重试</strong>:网络抖动自动重试3次</li>
<li><strong>Token计算</strong>:输入+输出不超模型上限</li>
<li><strong>流式优先</strong>:长文本用SSE流式输出</li>
</ol>
<h2>九、总结</h2>
<p>DeepSeek-V3 API兼容OpenAI格式,Spring Boot接入极简。核心:注册获取Key → 配置OkHttp → 构建请求 → 解析响应。生产环境建议加入限流、重试和Token计数。</p>

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

---

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

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

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

📚 本文地址:https://www.cnblogs.com/czlws/p/19853457/deepseek-v3-spring-boot-api-tutorial<br><br>
来源:https://www.cnblogs.com/czlws/p/19853457/deepseek-v3-spring-boot-api-tutorial
頁: [1]
查看完整版本: DeepSeek-V3 + Spring Boot实战:10分钟接入国产大模型API