从零构建一个基于 DeepSeek 的 AI 对话系统:Spring Boot + 前端实战指南
技术栈选型与准备
后端采用Spring Boot 3.x(Java 17+)提供RESTful API,前端使用Vue 3或React 18构建交互界面。DeepSeek API作为AI核心引擎,需提前申请API Key并了解其对话接口规范。数据库可选PostgreSQL或MySQL存储对话记录。
后端工程搭建
创建Spring Boot项目并添加必要依赖:
org.springframework.boot
spring-boot-starter-web
com.squareup.okhttp3
okhttp
4.10.0
配置application.yml设置DeepSeek参数:
deepseek:
api-key: YOUR_API_KEY
endpoint: https://api.deepseek.com/v1/chat/completions
核心服务层实现
创建AI服务代理类处理DeepSeek API调用:
@Service
public class AIService {
@Value("${deepseek.api-key}")
private String apiKey;
@Value("${deepseek.endpoint}")
private String endpoint;
public String getAIResponse(String userInput) throws IOException {
OkHttpClient client = new OkHttpClient();
MediaType JSON = MediaType.get("application/json");
String jsonBody = String.format("{"messages":[{"role":"user","content":"%s"}]}",
userInput.replace(""", "\""));
Request request = new Request.Builder()
.url(endpoint)
.addHeader("Authorization", "Bearer " + apiKey)
.post(RequestBody.create(jsonBody, JSON))
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
}
控制器设计
创建REST控制器暴露对话接口:
@RestController
@RequestMapping("/api/chat")
public class ChatController {
@Autowired
private AIService aiService;
@PostMapping
public ResponseEntity chat(@RequestBody Map request) {
try {
String response = aiService.getAIResponse(request.get("message"));
return ResponseEntity.ok(response);
} catch (IOException e) {
return ResponseEntity.status(500).build();
}
}
}
前端实现(Vue示例)
安装必要依赖:
npm install axios vue-router pinia
创建聊天组件:
{{ msg.role }}: {{ msg.content }}
增强功能实现
添加对话历史存储功能:
@Entity
public class Conversation {
@Id @GeneratedValue
private Long id;
private String sessionId;
@Lob
private String userMessage;
@Lob
private String aiResponse;
private LocalDateTime timestamp;
// Getters and setters
}
实现限流保护API:
@Configuration
public class RateLimitConfig implements WebMvcConfigurer {
@Bean
public FilterRegistrationBean rateLimitFilter() {
FilterRegistrationBean reg = new FilterRegistrationBean<>();
reg.setFilter(new RateLimitFilter(100, 1)); // 100 requests/minute
reg.addUrlPatterns("/api/chat");
return reg;
}
}
部署注意事项
- 使用Docker打包Spring Boot应用时,确保设置合理的内存限制
- 前端构建后可通过Nginx部署,配置API反向代理
- 生产环境应启用HTTPS并配置CORS策略
- 考虑实现API密钥轮换机制保障安全
性能优化建议
- 实现响应缓存减少重复查询
- 使用WebSocket替代HTTP轮询实现实时对话
- 添加对话摘要功能减少长文本传输
- 引入熔断机制防止API过载
完整项目应包含错误处理、日志监控、用户认证等生产级功能,上述代码提供基础实现框架,可根据实际需求扩展。






