当前位置: 首页 > news >正文

15分钟实战:SpringBoot + Vue2快速构建AI对话系统(集成DeepSeek)


15分钟实战:SpringBoot + Vue2快速构建AI对话系统(集成DeepSeek)

在这里插入图片描述


一、环境准备(2分钟)

1.1 技术栈清单

  • 后端:SpringBoot 2.7 + JDK 11
  • 前端:Vue2 + Axios
  • AI引擎: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 = "https://api.deepseek.com/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 测试效果

  1. 访问 http://localhost:8080
  2. 输入测试问题:“用Java实现快速排序”
  3. 查看返回结果:

示例:代码生成结果展示


五、常见问题排查

  1. API调用失败

    • 检查API密钥是否正确
    • 使用Postman测试原始接口
    curl -X POST https://api.deepseek.com/v1/chat/completions \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -d '{"model":"deepseek-r1","messages":[{"role":"user","content":"你好"}],"temperature":0.7}'
    
  2. 跨域问题

    • 确保后端已添加@CrossOrigin注解
    • 检查前端代理配置

六、项目优化建议

  1. 增加流式响应(SSE):
// 在Controller中添加
@GetMapping(path = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter streamChat(@RequestParam String message) {
    // 实现流式响应逻辑
}
  1. 添加对话历史管理
// 前端localStorage存储
localStorage.setItem('chatHistory', JSON.stringify(this.messages));

七、项目源码

获取完整代码:GitHub仓库链接
(此处替换为你的仓库地址)


技术总结:通过SpringBoot与Vue2的经典组合,我们快速实现了与DeepSeek的集成。这种架构具有以下优势:

  1. 快速迭代:前后端分离开发效率高
  2. 易于扩展:可轻松添加用户认证、历史记录等功能
  3. 生产就绪:SpringBoot的稳定性保障服务可靠性

下一步建议

  • 添加JWT认证
  • 实现消息持久化存储
  • 集成Redis缓存提升性能

原创声明:技术问题欢迎在评论区交流!


如果觉得本教程有帮助,请点赞收藏支持!关注作者获取更多SpringBoot与AI集成的实战技巧!

相关文章:

  • 进程间通信方式:对列、管道、共享内存
  • Oracle 数据库基础入门(四):分组与联表查询的深度探索(下)
  • 安路FPGA开发入门:软件安装与点灯与仿真(TangDynasty ModelSim)
  • VAE中的编码器(Encoder)详解
  • pg pg_prewarm用法
  • ICP-通过一组匹配的3D点估计相机运动
  • 【go】time.after内存泄漏
  • 使用 USRP 和 OpenAirInterface 构建实时神经接收器原型
  • 【Java项目】基于SpringBoot的超市进销存系统
  • React antd的datePicker自定义,封装成组件
  • 【数据挖掘】Pandas之DataFrame
  • 通过多线程同时获取H264和H265码流
  • 河道水位尺位数据集目标检测
  • 静态时序分析:SDC约束命令set_clock_jitter详解
  • halcon学习笔记1
  • 高效文件管理工具:一键生成文件清单,提升工作效率
  • Kneser-Ney平滑在自然语言处理中的应用
  • npm ERR! code 128 npm ERR! An unknown git error occurred
  • 一文讲清楚 MySQL 事务隔离级别和实现原理
  • 使用DeepSeek辅助编写一个快速排序算法程序的步骤
  • “光荣之城”2025上海红色文化季启动,红色主题市集亮相
  • 昂立教育:去年减亏1.39亿元,今年以“利润持续增长”为核心目标
  • 买新房可申领学位,广州南沙出台购房入学政策
  • AI应用大盘点:谁暴涨?谁掉队?
  • 著名统计学家、北京工业大学应用数理学院首任院长王松桂逝世
  • 体坛联播|皇马上演罢赛闹剧,杨瀚森宣布参加NBA选秀