简介:本文详细讲解如何使用SpringBoot后端与Vue2前端快速构建基于DeepSeek的AI对话系统,涵盖环境准备、接口对接、前后端集成及功能扩展,助力开发者10分钟内完成基础开发。
本文以“10分钟上手DeepSeek开发”为核心目标,通过SpringBoot+Vue2技术栈实现AI对话系统的快速构建。从环境准备、后端接口开发、前端交互设计到系统联调,提供分步骤的详细指导,并包含关键代码示例与优化建议,帮助开发者高效完成从0到1的AI应用开发。
spring-boot-starter-web依赖。
vue create deepseek-chat && cd deepseek-chatvue add element
YOUR_API_KEY)。创建HTTP客户端:使用RestTemplate或WebClient调用DeepSeek接口。
@RestController@RequestMapping("/api/chat")public class ChatController {@Value("${deepseek.api.key}")private String apiKey;@PostMapping("/generate")public ResponseEntity<String> generateResponse(@RequestBody ChatRequest request) {String url = "https://api.deepseek.com/v1/chat/completions";HttpHeaders headers = new HttpHeaders();headers.set("Authorization", "Bearer " + apiKey);headers.setContentType(MediaType.APPLICATION_JSON);Map<String, Object> body = new HashMap<>();body.put("model", "deepseek-chat");body.put("messages", Collections.singletonList(Map.of("role", "user", "content", request.getMessage())));HttpEntity<Map<String, Object>> entity = new HttpEntity<>(body, headers);ResponseEntity<String> response = new RestTemplate().postForEntity(url, entity, String.class);return response;}}
@ControllerAdvice捕获异常并返回标准化响应。
@ControllerAdvicepublic class GlobalExceptionHandler {@ExceptionHandler(Exception.class)public ResponseEntity<Map<String, String>> handleException(Exception e) {Map<String, String> body = new HashMap<>();body.put("error", e.getMessage());return ResponseEntity.status(500).body(body);}}
src/├── components/│ └── ChatWindow.vue # 对话窗口组件├── views/│ └── Home.vue # 主页面└── App.vue # 根组件
ChatWindow.vue示例:
<template><div class="chat-window"><div class="messages" v-for="msg in messages" :key="msg.id"><div :class="['message', msg.role]">{{ msg.content }}</div></div><div class="input-area"><el-input v-model="input" @keyup.enter="sendMessage"></el-input><el-button @click="sendMessage">发送</el-button></div></div></template><script>export default {data() {return {input: '',messages: []};},methods: {async sendMessage() {this.messages.push({ role: 'user', content: this.input });const response = await this.$http.post('/api/chat/generate', {message: this.input});this.messages.push({ role: 'bot', content: response.data });this.input = '';}}};</script>
Vuex集成:管理对话历史与加载状态。
// store/index.jsimport Vue from 'vue';import Vuex from 'vuex';Vue.use(Vuex);export default new Vuex.Store({state: {messages: []},mutations: {ADD_MESSAGE(state, { role, content }) {state.messages.push({ role, content });}},actions: {async sendMessage({ commit }, message) {commit('ADD_MESSAGE', { role: 'user', content: message });const response = await axios.post('/api/chat/generate', { message });commit('ADD_MESSAGE', { role: 'bot', content: response.data });}}});
Loading组件在等待响应时显示提示。@CrossOrigin注解或全局CORS配置。
@Configurationpublic class WebConfig implements WebMvcConfigurer {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**").allowedOrigins("*");}}
vue.config.js中配置代理。
module.exports = {devServer: {proxy: {'/api': {target: 'http://localhost:8080',changeOrigin: true}}}};
单元测试:使用JUnit测试后端接口。
@SpringBootTestpublic class ChatControllerTest {@Autowiredprivate ChatController chatController;@Testpublic void testGenerateResponse() {ChatRequest request = new ChatRequest("Hello");ResponseEntity<String> response = chatController.generateResponse(request);assertNotNull(response.getBody());}}
FROM openjdk:11-jreCOPY target/deepseek-chat.jar /app.jarENTRYPOINT ["java", "-jar", "/app.jar"]
通过SpringBoot+Vue2技术栈,开发者可在10分钟内完成DeepSeek AI对话系统的基础开发。后续可结合知识图谱、多模态交互等技术,进一步提升系统智能化水平。建议持续关注DeepSeek API的更新,优化对话模型与用户体验。