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

一、DeepSeek-V3 简介

DeepSeek-V3是深度求索推出的最新大语言模型,在代码生成和中文理解上表现优异。其API兼容OpenAI格式,开发者可零成本迁移。本文将手把手演示Spring Boot接入DeepSeek-V3 API。

二、获取API Key

1. 访问 platform.deepseek.com 注册账号

2. 进入API Keys页面,点击创建API Key

3. 复制Key(格式:sk-xxxxxxxx)

4. 新用户赠送500万Tokens额度

三、Spring Boot项目搭建

3.1 添加依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>com.squareup.okhttp3</groupId>
        <artifactId>okhttp</artifactId>
        <version>4.12.0</version>
    </dependency>
    <dependency>
        <groupId>com.alibaba.fastjson2</groupId>
        <artifactId>fastjson2</artifactId>
        <version>2.0.47</version>
    </dependency>
</dependencies>

3.2 配置文件

deepseek:
  api-key: sk-your-api-key-here
  base-url: https://api.deepseek.com
  model: deepseek-chat
  max-tokens: 2048
  temperature: 0.7

3.3 配置类

@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();
    }
}

四、核心服务实现

4.1 请求DTO

@Data
public class ChatRequest {
    private String model;
    private List<Message> 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;
    }
}

4.2 DeepSeek服务

@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);
        }
    }
}

五、流式响应SSE

@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: ") && !line.contains("[DONE]")) {
                        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;
}

六、Controller

@RestController
@RequestMapping("/api/deepseek")
public class DeepSeekController {
    @Autowired private DeepSeekService deepSeekService;

    @PostMapping("/chat")
    public Map<String, String> chat(@RequestBody Map<String, String> 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);
    }
}

七、测试

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

八、最佳实践

  1. API Key安全:用环境变量,勿硬编码
  2. 限流:加Semaphore限制并发
  3. 重试:网络抖动自动重试3次
  4. Token计算:输入+输出不超模型上限
  5. 流式优先:长文本用SSE流式输出

九、总结

DeepSeek-V3 API兼容OpenAI格式,Spring Boot接入极简。核心:注册获取Key → 配置OkHttp → 构建请求 → 解析响应。生产环境建议加入限流、重试和Token计数。

posted @ 2026-04-12 01:36  弥烟袅绕  阅读(0)  评论(0)    收藏  举报