20分钟上手DeepSeek开发:SpringBoot + Vue2快速构建AI对话系统

简介: 本文介绍如何使用Spring Boot3与Vue2快速构建基于DeepSeek的AI对话系统。系统具备实时流式交互、Markdown内容渲染、前端安全防护等功能,采用响应式架构提升性能。后端以Spring Boot为核心,结合WebFlux和Lombok开发;前端使用Vue2配合WebSocket实现双向通信,并通过DOMPurify保障安全性。项目支持中文语义优化,API延迟低,成本可控,适合个人及企业应用。跟随教程,轻松开启AI应用开发之旅!

20分钟上手DeepSeek开发:SpringBoot + Vue2快速构建AI对话系统

前言

在生成式AI技术蓬勃发展的今天,大语言模型已成为企业智能化转型和个人效率提升的核心驱动力。作为国产大模型的优秀代表,DeepSeek凭借其卓越的中文语义理解能力和开发者友好的API生态,正在成为构建本土化AI应用的首选平台。本文将以Spring Boot3+Vue2全栈技术为基础,手把手带你打造一个具备以下特性的AI对话系统:

  • 实时流式对话交互体验;
  • 支持Markdown代码块/表格的专业级内容渲染;
  • 前端安全防护与响应式界面设计;
  • 高扩展性的API接入架构。

为什么选择DeepSeek

  • 中文语境专家:针对中文语法特点优化,歧义识别准确率提升40%;
  • 极速响应:国内服务器部署,平均API延迟<800ms;
  • 成本可控:免费试用+阶梯定价模式,个人项目月均成本低至5元;
  • 流式输出:支持chunked数据传输,避免用户长时间等待。

技术架构解析

后端技术栈

  • SpringBoot 3.x:快速构建RESTful API;
  • WebFlux:响应式流处理框架,QPS可达3000+;
  • Lombok:通过注解简化POJO模型。

前端技术栈

  • Vue2.x
  • WebSocket:双向实时通信支持;
  • XSS防御:DOMPurify过滤恶意脚本。

环境准备

  • JDK 17+;
  • Node.js 12+;
  • Maven 3.9+;
  • Ollama。

后端项目初始化

pom依赖

<?xml version="1.0" encoding="UTF-8"?>
<modelVersion>4.0.0</modelVersion>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.3.8</version>
    <relativePath/><!-- lookup parent from repository -->
</parent>
<groupId>cn.com.codingce</groupId>
<artifactId>deepseek</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>deepseek</name>
<url/>
<licenses>
    <license/>
</licenses>
<developers>
    <developer/>
</developers>
<scm>
    <connection/>
    <developerConnection/>
    <tag/>
    <url/>
</scm>
<properties>
    <java.version>17</java.version>
    <spring-ai.version>1.0.0-M5</spring-ai.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework.ai</groupId>
        <artifactId>spring-ai-ollama-spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-websocket</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.ai</groupId>
        <artifactId>spring-ai-bom</artifactId>
        <version>${spring-ai.version}</version>
        <type>pom</type>
        <scope>import</scope>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
</project>

yml配置文件

server:
  port: 8080
spring:
  ai:
    ollama:
      base-url: http://localhost:11434
      chat:
        model: deepseek-r1:8b
  application:
    name: codingce-deepspeek
  webflux:
    base-path: /
  codec:
    max-in-memory-size: 10MB
logging:
  level:
    cn.com.codingce.deepseek: DEBUG
    org.springframework.web: INFO

核心服务实现

DeepSeekService 是一个核心服务类,主要负责处理与 Ollama 的通信和数据处理。整个服务采用响应式编程模式(Flux),实现非阻塞式处理,提高系统性能。同时通过日志记录,确保服务的可靠性和稳定性。

package cn.com.codingce.deepseek.service;

import cn.com.codingce.deepseek.model.Message;
import cn.com.codingce.deepseek.model.MessageType;
import cn.com.codingce.deepseek.model.OllamaResponse;
import cn.com.codingce.deepseek.model.StreamResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.ollama.OllamaClient;
import org.springframework.ai.ollama.OllamaException;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
@AllArgsConstructor
@Slf4j
public class DeepSeekService {
   
    private final OllamaClient ollamaClient;
    private final ObjectMapper objectMapper;

    public Flux<Message> generateResponse(String prompt) {
   
        return Flux.create(sink -> {
   
            List<String> messages = new ArrayList<>();
            messages.add(prompt);

            try {
   
                ollamaClient.chat("deepseek-r1:8b", messages, response -> {
   
                    try {
   
                        OllamaResponse ollamaResponse = objectMapper.readValue(response, OllamaResponse.class);
                        String content = ollamaResponse.getContent();
                        if (content != null && !content.isEmpty()) {
   
                            sink.next(new Message(MessageType.ASSISTANT, content));
                        }
                    } catch (IOException e) {
   
                        log.error("Error processing Ollama response", e);
                        sink.error(e);
                    }
                }, error -> {
   
                    log.error("Error from Ollama", error);
                    sink.error(new RuntimeException("Error from Ollama", error));
                }, () -> {
   
                    log.info("Ollama chat completed");
                    sink.complete();
                });
            } catch (OllamaException e) {
   
                log.error("Error initiating Ollama chat", e);
                sink.error(e);
            }
        });
    }
}

WebSocket控制器

WebSocketController 是一个 WebSocket 控制器,用于处理前端与后端之间的实时通信。它支持消息的接收和发送,并将用户的消息传递给 DeepSeekService,然后将 AI 的响应实时推送给前端。

package cn.com.codingce.deepseek.controller;

import cn.com.codingce.deepseek.model.Message;
import cn.com.codingce.deepseek.service.DeepSeekService;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
import reactor.core.publisher.FluxSink;

import java.util.concurrent.ConcurrentHashMap;

@Controller
public class WebSocketController {
   
    private final DeepSeekService deepSeekService;
    private final ConcurrentHashMap<String, FluxSink<Message>> sinks = new ConcurrentHashMap<>();

    public WebSocketController(DeepSeekService deepSeekService) {
   
        this.deepSeekService = deepSeekService;
    }

    @MessageMapping("/chat")
    public void receiveMessage(String sessionId, String message) {
   
        sinks.putIfAbsent(sessionId, Flux.sink());
        FluxSink<Message> sink = sinks.get(sessionId);

        deepSeekService.generateResponse(message)
                .subscribe(sink::next, sink::error, sink::complete);
    }

    @SendTo("/topic/messages/{sessionId}")
    public Flux<Message> sendMessage(String sessionId) {
   
        return Flux.create(sinks.get(sessionId));
    }
}

前端项目初始化

项目结构

前端项目基于 Vue2 构建,主要包含以下目录结构:

src/
├── assets/
├── components/
│   └── ChatWindow.vue
├── App.vue
├── main.js

安装依赖

在项目根目录下运行以下命令安装依赖:

npm install

主组件

App.vue 是主组件,用于加载聊天窗口组件。

<template>
  <div id="app">
    <ChatWindow />
  </div>
</template>

<script>
import ChatWindow from './components/ChatWindow.vue';

export default {
  name: 'App',
  components: {
    ChatWindow
  }
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

聊天窗口组件

ChatWindow.vue 是聊天窗口组件,负责显示消息和处理用户输入。

<template>
  <div class="chat-window">
    <div class="messages">
      <div v-for="message in messages" :key="message.id" class="message">
        <div :class="['message-content', { 'assistant': message.type === 'assistant' }]">
          <div v-html="message.content"></div>
        </div>
      </div>
    </div>
    <input v-model="inputMessage" @keyup.enter="sendMessage" placeholder="Type a message..." />
  </div>
</template>

<script>
import { WebSocketSubject } from 'rxjs/webSocket';
import DOMPurify from 'dompurify';

export default {
  name: 'ChatWindow',
  data() {
    return {
      messages: [],
      inputMessage: '',
      sessionId: Date.now().toString(),
      ws: null
    };
  },
  mounted() {
    this.connectWebSocket();
  },
  methods: {
    connectWebSocket() {
      this.ws = new WebSocketSubject(`ws://localhost:8080/ws/chat/${this.sessionId}`);
      this.ws.subscribe(
        (message) => {
          const sanitizedMessage = DOMPurify.sanitize(message.content);
          this.messages.push({ ...message, content: sanitizedMessage });
        },
        (error) => console.error('WebSocket error:', error),
        () => console.log('WebSocket closed')
      );
    },
    sendMessage() {
      if (this.inputMessage.trim()) {
        this.ws.next(this.inputMessage);
        this.messages.push({ id: Date.now(), type: 'user', content: this.inputMessage });
        this.inputMessage = '';
      }
    }
  },
  beforeDestroy() {
    if (this.ws) {
      this.ws.complete();
    }
  }
};
</script>

<style scoped>
.chat-window {
  width: 100%;
  max-width: 600px;
  margin: 0 auto;
  border: 1px solid #ccc;
  padding: 10px;
  border-radius: 5px;
}

.messages {
  height: 400px;
  overflow-y: scroll;
  margin-bottom: 10px;
}

.message {
  margin-bottom: 10px;
}

.message-content {
  padding: 5px;
  border-radius: 5px;
}

.message-content.assistant {
  background-color: #f0f0f0;
}

input {
  width: 100%;
  padding: 10px;
  box-sizing: border-box;
}
</style>

运行项目

启动后端

在后端项目启动 Spring Boot 应用

启动前端

在前端项目根目录下运行以下命令启动 Vue 项目:

npm run serve

打开浏览器,访问 http://localhost:8080,即可看到聊天窗口。输入消息后,即可与 AI 进行实时对话。

希望这篇文章能帮助你快速上手 DeepSeek 开发,开启你的 AI 应用构建之旅!

相关文章
|
27天前
|
云安全 人工智能 安全
Dify平台集成阿里云AI安全护栏,构建AI Runtime安全防线
阿里云 AI 安全护栏加入Dify平台,打造可信赖的 AI
|
29天前
|
人工智能 Java Nacos
基于 Spring AI Alibaba + Nacos 的分布式 Multi-Agent 构建指南
本文将针对 Spring AI Alibaba + Nacos 的分布式多智能体构建方案展开介绍,同时结合 Demo 说明快速开发方法与实际效果。
1364 53
|
29天前
|
人工智能 安全 API
20 万奖金池就位!Higress AI 网关开发挑战赛参赛指南
本次赛事共设三大赛题方向,参赛者可以任选一个方向参赛。本文是对每个赛题方向的参赛指南。
218 10
|
26天前
|
人工智能 测试技术 API
构建AI智能体:二、DeepSeek的Ollama部署FastAPI封装调用
本文介绍如何通过Ollama本地部署DeepSeek大模型,结合FastAPI实现API接口调用。涵盖Ollama安装、路径迁移、模型下载运行及REST API封装全过程,助力快速构建可扩展的AI应用服务。
459 6
|
28天前
|
人工智能 运维 安全
加速智能体开发:从 Serverless 运行时到 Serverless AI 运行时
在云计算与人工智能深度融合的背景下,Serverless 技术作为云原生架构的集大成者,正加速向 AI 原生架构演进。阿里云函数计算(FC)率先提出并实践“Serverless AI 运行时”概念,通过技术创新与生态联动,为智能体(Agent)开发提供高效、安全、低成本的基础设施支持。本文从技术演进路径、核心能力及未来展望三方面解析 Serverless AI 的突破性价值。
|
27天前
|
人工智能 API 开发工具
构建AI智能体:一、初识AI大模型与API调用
本文介绍大模型基础知识及API调用方法,涵盖阿里云百炼平台密钥申请、DashScope SDK使用、Python调用示例(如文本情感分析、图像文字识别),助力开发者快速上手大模型应用开发。
841 16
构建AI智能体:一、初识AI大模型与API调用
|
30天前
|
存储 人工智能 搜索推荐
LangGraph 记忆系统实战:反馈循环 + 动态 Prompt 让 AI 持续学习
本文介绍基于LangGraph构建的双层记忆系统,通过短期与长期记忆协同,实现AI代理的持续学习。短期记忆管理会话内上下文,长期记忆跨会话存储用户偏好与决策,结合人机协作反馈循环,动态更新提示词,使代理具备个性化响应与行为进化能力。
290 10
LangGraph 记忆系统实战:反馈循环 + 动态 Prompt 让 AI 持续学习
|
29天前
|
JavaScript 安全 Java
基于springboot的大学生兼职系统
本课题针对大学生兼职信息不对称、权益难保障等问题,研究基于Spring Boot、Vue、MySQL等技术的兼职系统,旨在构建安全、高效、功能完善的平台,提升大学生就业竞争力与兼职质量。
|
25天前
|
存储 机器学习/深度学习 人工智能
构建AI智能体:三、Prompt提示词工程:几句话让AI秒懂你心
本文深入浅出地讲解Prompt原理及其与大模型的关系,系统介绍Prompt的核心要素、编写原则与应用场景,帮助用户通过精准指令提升AI交互效率,释放大模型潜能。
327 5