
JAVA接入DeepSeek R1满血版,附带源代码以及注释,还有接入方法,教程!Java调用本地部署的deepseek!
JAVA接入DeepSeek R1满血版,附带源代码以及注释,还有接入方法,教程!Java调用本地部署的deepseek!以下为基于 Java 技术栈快速实现 DeepSeek 大模型调用的综合方案,整合了多篇技术实践文档的核心内容
deepseek-java-demo 开发指南
以下为基于 Java 技术栈快速实现 DeepSeek 大模型调用的综合方案,整合了多篇技术实践文档的核心内容:
一、环境配置
- 基础要求
JDK 17 及以上版本(推荐 JDK 21)
Spring Boot 3.3.6+(若使用 Spring AI 需注意版本兼容性)
Maven/Gradle 依赖管理工具
- 依赖配置(Maven 示例)
<!-- 基础依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- HTTP 客户端 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<!-- JSON 解析 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version>
</dependency>
<!-- Spring AI (可选) -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
</dependency>
二、API Key 配置
- 获取密钥
登录 DeepSeek 官网 → API 开放平台 → 创建 API Key(需妥善保存)
-
安全存储
推荐通过环境变量或加密配置文件管理:
# application.yml ai: deepseek: api-key: ${DEEPSEEK_API_KEY} # 从环境变量读取 base-url: https://api.deepseek.com/v1
三、核心代码示例
方案 1
:通过 HTTPClient 调用
@RestController
public class DeepSeekController {
@Value("${ai.deepseek.api-key}")
private String apiKey;
@PostMapping("/chat")
public String chat(@RequestBody String prompt) throws IOException {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost("https://api.deepseek.com/v1/chat/completions");
post.setHeader("Authorization", "Bearer " + apiKey);
post.setHeader("Content-Type", "application/json");
String jsonBody = String.format("{\"model\": \"deepseek-r1\", \"messages\": [{\"role\": \"user\", \"content\": \"%s\"}]}", prompt);
post.setEntity(new StringEntity(jsonBody));
try (CloseableHttpResponse response = client.execute(post)) {
return EntityUtils.toString(response.getEntity());
}
}
}
方案 2
:通过 Spring AI 集成
# application.yml
spring:
ai:
openai:
base-url: https://api.deepseek.com/v1
api-key: ${DEEPSEEK_API_KEY}
@RestController
public class AIController {
@Autowired
private OpenAiChatClient chatClient;
@GetMapping("/ask")
public String ask(@RequestParam String question) {
return chatClient.call(question);
}
}
四、常见问题与优化
- SSL 证书异常
若出现 PKIX path building failed 错误,需导入 DeepSeek 的 SSL 证书到 Java 信任库7。
2. 流式输出实现
使用 HttpClient 结合 InputStream 实现分块读取响应,参考 Spring AI 的流式处理逻辑6。
3. 多轮会话管理
通过维护 List 对象保存历史对话上下文6。
五、部署方式
1. 本地部署
结合 Ollama 工具拉取 DeepSeek 模型(需科学上网)。
- 云服务调用
直接通过 API 调用云端模型(需注意网络稳定性)。
以上方案可结合实际需求选择,完整代码示例可参考 GitHub 开源项目或技术博客源码。
六、部分截图
移动端截图:
暗黑主题截图:
演示示例:
演示地址:点击前往
源码下载:
下载地址:点击下载
更多推荐
所有评论(0)