SpringBoot 集成 DeepSeek 大模型——从零到一实现 AI 接口调用

在企业级开发中,将主流大模型与 SpringBoot 后端框架集成,能快速为项目赋予AI能力(如智能问答、文本生成、代码解析等)。DeepSeek(深度求索)作为国产高性能大模型,提供了标准的 OpenAI 兼容接口,无需复杂适配,SpringBoot 项目可直接通过 HTTP 调用其 API 实现集成。

本文将手把手教你:SpringBoot 项目快速集成 DeepSeek 大模型,包含依赖引入、配置、核心代码编写、接口测试,开箱即用。

一、前期准备

1. 申请 DeepSeek API 密钥

  1. 访问 DeepSeek 开放平台
  2. 注册/登录账号 → 进入「API 密钥管理」
  3. 创建新的 API Key(保存好,代码中会用到

2. 核心说明

DeepSeek 提供标准 OpenAI 格式接口,我们无需自定义复杂 SDK,直接用 SpringBoot 的 RestTemplate/WebClient 调用即可。

  • 接口地址:https://api.deepseek.com/chat/completions
  • 支持模型:deepseek-chat(对话模型)、deepseek-coder(代码模型)

二、SpringBoot 项目搭建与依赖引入

1. 创建 SpringBoot 项目

新建 SpringBoot 项目(推荐 3.x 版本),选择核心依赖:

<!-- SpringBoot Web 核心依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- lombok 简化代码 -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

三、application.yml 配置

将 DeepSeek 的接口地址、API 密钥、模型名称统一配置,方便维护:

spring:
  application:
    name: springboot-deepseek-demo

# DeepSeek 配置
deepseek:
  # API 地址(固定)
  api-url: https://api.deepseek.com/chat/completions
  # 你的 API Key
  api-key: sk-xxxxxxxxxxxxxxxxxxxxxxxx
  # 使用的模型
  model: deepseek-chat
  # 温度参数(0-2,值越小回答越精准,值越大越有创意)
  temperature: 0.7

四、核心代码实现

1. 配置类:注册 RestTemplate

用于发送 HTTP 请求调用 DeepSeek API:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

2. 实体类:请求/响应参数封装

(1)DeepSeek 请求实体

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;

/**
 * DeepSeek API 请求参数
 */
@Data
public class DeepSeekRequest {
    // 模型名称
    private String model;
    // 对话消息列表
    private List<Message> messages;
    // 温度参数
    private Double temperature;

    // 消息内部类
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class Message {
        // 角色:user(用户) / assistant(AI) / system(系统提示)
        private String role;
        // 消息内容
        private String content;
    }
}

(2)DeepSeek 响应实体

import lombok.Data;
import java.util.List;

/**
 * DeepSeek API 响应参数
 */
@Data
public class DeepSeekResponse {
    // 响应ID
    private String id;
    // 模型名称
    private String model;
    // 回答结果列表
    private List<Choice> choices;

    @Data
    public static class Choice {
        // 消息内容
        private DeepSeekRequest.Message message;
        // 结束原因
        private String finish_reason;
    }
}

3. Service 层:核心调用逻辑

封装 DeepSeek API 调用方法,解耦业务逻辑:

import com.example.springbootdeepseek.entity.DeepSeekRequest;
import com.example.springbootdeepseek.entity.DeepSeekResponse;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.Collections;

@Service
public class DeepSeekService {

    @Resource
    private RestTemplate restTemplate;

    // 从配置文件读取参数
    @Value("${deepseek.api-url}")
    private String apiUrl;

    @Value("${deepseek.api-key}")
    private String apiKey;

    @Value("${deepseek.model}")
    private String model;

    @Value("${deepseek.temperature}")
    private Double temperature;

    /**
     * 调用 DeepSeek 大模型获取回答
     * @param userPrompt 用户问题
     * @return AI 回答内容
     */
    public String chat(String userPrompt) {
        // 1. 构建请求头(必须携带 API Key 认证)
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + apiKey);
        headers.set("Content-Type", "application/json");

        // 2. 构建请求体
        DeepSeekRequest request = new DeepSeekRequest();
        request.setModel(model);
        request.setTemperature(temperature);
        // 封装用户消息
        DeepSeekRequest.Message message = new DeepSeekRequest.Message("user", userPrompt);
        request.setMessages(Collections.singletonList(message));

        // 3. 发送请求
        HttpEntity<DeepSeekRequest> httpEntity = new HttpEntity<>(request, headers);
        DeepSeekResponse response = restTemplate.exchange(
                apiUrl,
                HttpMethod.POST,
                httpEntity,
                DeepSeekResponse.class
        ).getBody();

        // 4. 解析并返回 AI 回答
        if (response != null && !response.getChoices().isEmpty()) {
            return response.getChoices().get(0).getMessage().getContent();
        }
        return "AI 回答为空";
    }
}

4. Controller 层:对外提供接口

提供 HTTP 接口,供前端/其他服务调用:

import com.example.springbootdeepseek.service.DeepSeekService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/ai")
public class DeepSeekController {

    @Resource
    private DeepSeekService deepSeekService;

    /**
     * AI 对话接口
     * @param message 用户问题
     * @return AI 回答
     */
    @GetMapping("/chat")
    public String chat(@RequestParam String message) {
        return deepSeekService.chat(message);
    }
}

五、项目测试

1. 启动 SpringBoot 项目

2. 调用接口

浏览器/Postman 访问:

http://localhost:8080/ai/chat?message=用Java写一个冒泡排序

3. 响应结果

项目会直接返回 DeepSeek 大模型生成的答案:

以下是Java实现的冒泡排序代码:
public class BubbleSort {
    public static void main(String[] args) {
        int[] arr = {5, 2, 9, 1, 5, 6};
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }
}

六、进阶优化(生产环境必备)

1. 超时配置

避免接口调用阻塞,给 RestTemplate 设置超时时间:

@Bean
public RestTemplate restTemplate() {
    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
    factory.setConnectTimeout(5000); // 连接超时5秒
    factory.setReadTimeout(30000);  // 读取超时30秒
    return new RestTemplate(factory);
}

2. 全局异常处理

捕获 API 调用异常(如密钥错误、网络超时、模型限流):

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public String handleException(Exception e) {
        log.error("AI接口调用失败:{}", e.getMessage());
        return "AI服务暂时不可用,请稍后重试";
    }
}

3. 支持上下文对话

修改代码,传递历史消息,实现多轮对话。

4. 流式响应

对接 DeepSeek 流式输出接口,实现打字机效果(适合前端对话场景)。


七、常见问题

  1. API Key 错误:返回 401 异常 → 检查配置文件中的 API Key 是否正确。
  2. 接口超时:返回 504 异常 → 增大 RestTemplate 超时时间。
  3. 请求频率超限:DeepSeek 免费版有调用次数限制 → 升级账号或降低调用频率。

总结

  1. SpringBoot 集成 DeepSeek 核心是调用其标准 HTTP 接口,无侵入、低代码。
  2. 核心流程:配置密钥 → 封装请求参数 → 发送 HTTP 请求 → 解析响应结果。
  3. 生产环境需添加超时控制、异常处理、限流等优化,保证服务稳定性。
  4. 可快速扩展能力:代码生成、文本总结、智能客服、AI 助手等。

整套代码可直接复制运行,是 SpringBoot + 大模型集成的最佳实践方案!


作 者:南烛
链 接:https://www.itnotes.top/archives/1420
来 源:IT笔记
文章版权归作者所有,转载请注明出处!


上一篇
下一篇