15分钟实战:SpringBoot+Vue2快速构建AI对话系统(集成DeepSeek)
- 其他
- 2025-09-13 21:03:02

15分钟实战:SpringBoot + Vue2快速构建AI对话系统(集成DeepSeek)
一、环境准备(2分钟) 1.1 技术栈清单 后端:SpringBoot 2.7 + JDK 11前端:Vue2 + AxiosAI引擎:DeepSeek API工具:Postman、IDEA、VS Code 1.2 快速初始化 # 创建SpringBoot项目 spring init --dependencies=web,devtools ai-backend # 创建Vue2项目 vue create ai-frontend --preset default
二、后端开发(6分钟) 2.1 添加API请求工具类 // src/main/java/com/example/util/ApiClient.java public class ApiClient { private static final String DEEPSEEK_URL = " api.deepseek /v1/chat/completions"; public static String getAIResponse(String prompt, String apiKey) throws IOException { OkHttpClient client = new OkHttpClient(); MediaType mediaType = MediaType.parse("application/json"); String jsonBody = String.format("{\"model\":\"deepseek-r1\",\"messages\":[{\"role\":\"user\",\"content\":\"%s\"}],\"temperature\":0.7}", prompt.replace("\"", "\\\"")); Request request = new Request.Builder() .url(DEEPSEEK_URL) .post(RequestBody.create(mediaType, jsonBody)) .addHeader("Authorization", "Bearer " + apiKey) .build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); return response.body().string(); } } } 2.2 创建控制器 // src/main/java/com/example/controller/AIController.java @RestController @CrossOrigin("*") public class AIController { @Value("${deepseek.api.key}") private String apiKey; @PostMapping("/chat") public ResponseEntity<String> chat(@RequestBody Map<String, String> request) { try { String response = ApiClient.getAIResponse(request.get("message"), apiKey); return ResponseEntity.ok(response); } catch (IOException e) { return ResponseEntity.status(500).body("{\"error\":\"API请求失败\"}"); } } } 2.3 配置application.properties # 填入你的DeepSeek API Key deepseek.api.key=your_api_key_here server.port=8080
三、前端开发(5分钟) 3.1 实现聊天界面 <!-- src/components/ChatWindow.vue --> <template> <div class="chat-container"> <div class="message-area"> <div v-for="(msg, index) in messages" :key="index"> <div :class="['message', msg.role]">{{ msg.content }}</div> </div> </div> <div class="input-area"> <input v-model="inputMessage" @keyup.enter="sendMessage"/> <button @click="sendMessage">发送</button> </div> </div> </template> <script> import axios from 'axios'; export default { data() { return { inputMessage: '', messages: [] }; }, methods: { async sendMessage() { if (!this.inputMessage.trim()) return; const userMsg = { role: 'user', content: this.inputMessage }; this.messages.push(userMsg); try { const response = await axios.post('http://localhost:8080/chat', { message: this.inputMessage }); const aiMsg = { role: 'assistant', content: JSON.parse(response.data).choices[0].message.content }; this.messages.push(aiMsg); } catch (error) { console.error('请求失败:', error); } this.inputMessage = ''; } } }; </script> <style scoped> .chat-container { /* 样式代码省略 */ } </style> 3.2 配置代理(解决跨域) // vue.config.js module.exports = { devServer: { proxy: { '/api': { target: 'http://localhost:8080', changeOrigin: true, pathRewrite: { '^/api': '' } } } } }
四、运行与测试(2分钟) 4.1 启动服务 # 后端启动 cd ai-backend && mvn spring-boot:run # 前端启动 cd ai-frontend && npm run serve 4.2 测试效果 访问 http://localhost:8080输入测试问题:“用Java实现快速排序”查看返回结果:
示例:代码生成结果展示
五、常见问题排查
API调用失败:
检查API密钥是否正确使用Postman测试原始接口 curl -X POST api.deepseek /v1/chat/completions \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{"model":"deepseek-r1","messages":[{"role":"user","content":"你好"}],"temperature":0.7}'跨域问题:
确保后端已添加@CrossOrigin注解检查前端代理配置六、项目优化建议 增加流式响应(SSE): // 在Controller中添加 @GetMapping(path = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public SseEmitter streamChat(@RequestParam String message) { // 实现流式响应逻辑 } 添加对话历史管理: // 前端localStorage存储 localStorage.setItem('chatHistory', JSON.stringify(this.messages));
七、项目源码
获取完整代码:GitHub仓库链接 (此处替换为你的仓库地址)
技术总结:通过SpringBoot与Vue2的经典组合,我们快速实现了与DeepSeek的集成。这种架构具有以下优势:
快速迭代:前后端分离开发效率高易于扩展:可轻松添加用户认证、历史记录等功能生产就绪:SpringBoot的稳定性保障服务可靠性下一步建议:
添加JWT认证实现消息持久化存储集成Redis缓存提升性能原创声明:技术问题欢迎在评论区交流!
如果觉得本教程有帮助,请点赞收藏支持!关注作者获取更多SpringBoot与AI集成的实战技巧!
15分钟实战:SpringBoot+Vue2快速构建AI对话系统(集成DeepSeek)由讯客互联其他栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“15分钟实战:SpringBoot+Vue2快速构建AI对话系统(集成DeepSeek)”
 
               
               
               
               
               
               
               
               
   
   
   
   
   
   
   
   
   
   
  