从零构建一个基于 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项目并添加必要依赖:

XML 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.10.0</version>
</dependency>

配置application.yml设置DeepSeek参数:

yaml 复制代码
deepseek:
  api-key: YOUR_API_KEY
  endpoint: https://api.deepseek.com/v1/chat/completions

核心服务层实现

创建AI服务代理类处理DeepSeek API调用:

java 复制代码
@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控制器暴露对话接口:

java 复制代码
@RestController
@RequestMapping("/api/chat")
public class ChatController {
    @Autowired
    private AIService aiService;
    
    @PostMapping
    public ResponseEntity<String> chat(@RequestBody Map<String, String> request) {
        try {
            String response = aiService.getAIResponse(request.get("message"));
            return ResponseEntity.ok(response);
        } catch (IOException e) {
            return ResponseEntity.status(500).build();
        }
    }
}

前端实现(Vue示例)

安装必要依赖:

bash 复制代码
npm install axios vue-router pinia

创建聊天组件:

vue 复制代码
<script setup>
import { ref } from 'vue'
import axios from 'axios'

const messages = ref([])
const userInput = ref('')

const sendMessage = async () => {
  if (!userInput.value.trim()) return
  
  messages.value.push({ role: 'user', content: userInput.value })
  const tempInput = userInput.value
  userInput.value = ''
  
  try {
    const { data } = await axios.post('/api/chat', {
      message: tempInput
    })
    messages.value.push({ role: 'assistant', content: data.choices[0].message.content })
  } catch (error) {
    console.error('API Error:', error)
  }
}
</script>

<template>
  <div class="chat-container">
    <div v-for="(msg, index) in messages" :key="index">
      <strong>{{ msg.role }}:</strong> {{ msg.content }}
    </div>
    <input v-model="userInput" @keyup.enter="sendMessage" />
    <button @click="sendMessage">Send</button>
  </div>
</template>

增强功能实现

添加对话历史存储功能:

java 复制代码
@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:

java 复制代码
@Configuration
public class RateLimitConfig implements WebMvcConfigurer {
    @Bean
    public FilterRegistrationBean<RateLimitFilter> rateLimitFilter() {
        FilterRegistrationBean<RateLimitFilter> reg = new FilterRegistrationBean<>();
        reg.setFilter(new RateLimitFilter(100, 1)); // 100 requests/minute
        reg.addUrlPatterns("/api/chat");
        return reg;
    }
}

部署注意事项

  1. 使用Docker打包Spring Boot应用时,确保设置合理的内存限制
  2. 前端构建后可通过Nginx部署,配置API反向代理
  3. 生产环境应启用HTTPS并配置CORS策略
  4. 考虑实现API密钥轮换机制保障安全

性能优化建议

  1. 实现响应缓存减少重复查询
  2. 使用WebSocket替代HTTP轮询实现实时对话
  3. 添加对话摘要功能减少长文本传输
  4. 引入熔断机制防止API过载

完整项目应包含错误处理、日志监控、用户认证等生产级功能,上述代码提供基础实现框架,可根据实际需求扩展。

相关推荐
ssxueyi2 小时前
用 Claude Code 从零开发自己的Direct3D 硬件加速播放器
ffmpeg·ai编程·directx·视频播放器·从零开始·claude code·csdn征文活动
csdn2015_2 小时前
Spring Boot `HttpServletRequest`
spring boot·http·servlet
小沈同学呀2 小时前
SpringBoot 使用Docx4j实现 DOCX 转 PDF
spring boot·后端·pdf·docx4j
计算机学姐2 小时前
基于SpringBoot的校园流浪动物救助平台
java·spring boot·后端·spring·java-ee·tomcat·intellij-idea
想要一只奶牛猫2 小时前
SpringBoot 配置文件
java·spring boot·后端
那我掉的头发算什么2 小时前
【Mybatis】动态SQL与留言板小项目
数据库·spring boot·sql·spring·mybatis·配置
有诺千金2 小时前
SpringBoot3的前后端分离架构中使用SpringSecurity的思路
spring boot·架构
Warren982 小时前
一次文件上传异常的踩坑、定位与修复复盘(Spring Boot + 接口测试)
java·开发语言·spring boot·笔记·后端·python·面试
indexsunny2 小时前
互联网大厂Java面试实录:Spring Boot微服务与Kafka消息队列实战解析
java·spring boot·微服务·面试·kafka·电商·技术解析