Spring Boot3+Vue2极速整合: 10分钟搭建DeepSeek 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"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<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>
	<description>微信公众号: 后端码匠</description>
	<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>

	</dependencies>
	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.ai</groupId>
				<artifactId>spring-ai-bom</artifactId>
				<version>${spring-ai.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<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 lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.ollama.OllamaChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

/**
 * @author 后端码匠
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DeepSeekService {

    private final OllamaChatModel ollamaChatModel;

    public Flux<String> handleChatWebSocket(String question) {
        return sendChatRequest(question)
                .doOnNext(response -> log.info("handleChatWebSocket 发送响应: {}", response))
                .onErrorResume(e -> {
                    log.error("handleChatWebSocket WebSocket通信错误: {}", e.getMessage());
                    return Flux.just("抱歉, 服务器处理请求时发生错误, 请稍后重试.");
                });
    }

    public Flux<String> sendChatRequest(String question) {

        String res = ollamaChatModel.call(question);

        log.info("sendChatRequest 回答: {}", res);

        return Flux.just(res);
    }

}

前端项目初始化

vue create codingce-deepspeek-front
cd codingce-deepspeek-front
npm install sockjs-client marked dompurify

聊天组件ChatCodingce.vue开发

采用 flex 布局、基于 WebSocket 进行实时通信、针对不同类型的消息等。

  • 采用 flex 布局,包含消息显示区、输入区和连接状态提示区。消息显示区支持滚动,并能自动定位到最新消息;输入区集成了输入框和发送按钮,提供便捷的交互体验;状态区则实时显示 WebSocket 连接状态,让用户随时掌握通信情况。

  • 基于 WebSocket 进行实时通信,initWebSocket 方法负责建立连接,并完整管理连接生命周期,包括连接成功、消息接收、错误处理和断线重连等。消息的发送与接收分别通过 sendMessage 和 appendMessage 方法处理,并支持区分用户消息和机器人回复。此外,组件使用 marked 库渲染 Markdown 格式,并结合 DOMPurify 进行 XSS 过滤,确保消息展示安全可靠。

  • 针对不同类型的消息(用户消息、机器人回复、错误提示)定义了个性化样式,并利用 :deep 选择器为 Markdown 内容提供精细化样式支持,包括标题、代码块、表格、列表等,确保内容展示既专业又美观。整体设计注重用户体验,不仅优化了交互细节,还完善了状态提示和错误处理机制,使聊天体验更加流畅。

<template>
  <div class="chat-container">
    <div class="message-container" ref="messageContainer">
      <div 
        v-for="(message, index) in messages" 
        :key="index"
        :class="['message', message.type + '-message']"
      >
        <div v-if="message.type === 'bot'" v-html="renderMarkdown(message.content)"></div>
        <div v-else>{{ message.content }}</div>
      </div>
    </div>
    <div class="input-container">
      <input 
        v-model="inputMessage" 
        @keyup.enter="sendMessage"
        placeholder="输入您的问题...(微信公众号:后端码匠)"
        class="message-input"
        :disabled="!isConnected"
      >
      <button 
        @click="sendMessage" 
        class="send-button"
        :disabled="!isConnected"
      >
        发送
      </button>
    </div>
    <div v-if="!isConnected" class="connection-status">
      连接已断开,正在重新连接...
    </div>
  </div>
</template>
...

效果展示

后端


上图显示了项目运行时的日志信息,记录了 WebSocket 连接和 ollama 的交互过程,包括消息接收和响应的详细日志。

前端

上图为 AI 对话系统的用户界面截图。整个界面支持 Markdown 格式的渲染,使得回答内容层次分明,易于阅读。

源码获取

关注gzh后端码匠,回复"DeepSeek"消息即可获取完整源码。

结语

通过本文的实践,我们成功搭建了一个基于 Spring Boot 和 Vue 的 AI 对话系统。该系统具备以下特点:

  • 实时对话 基于 WebSocket 实现流式响应,带来更流畅的交互体验;
  • 优雅展示 支持 Markdown 格式渲染,让消息显示更清晰直观;
  • 稳定可靠 内置完善的错误处理机制,确保系统高效稳定运行;
  • 易于扩展 代码结构清晰,方便后续功能拓展和优化。

这一系统不仅能够用于智能客服 在线问答等场景,还能结合大模型能力,进一步提升智能化水平。未来,我们可以继续优化性能,增强上下文理解能力,并探索更多创新应用场景,让 AI 交互变得更加智能自然。

### Spring BootVue 项目接入 DeepSeek 的教程 #### 1. 准备工作 为了将 Spring BootVue 项目成功接入本地的 DeepSeek,需先完成必要的准备工作。 确保已安装并配置好 Java 开发环境以及 Node.js 环境。此外,还需下载并设置 DeepSeek SDK 或者按照官方文档指导来获取访问凭证[^1]。 #### 2. 创建 Spring Boot 应用程序 创建一个新的 Spring Boot 工程,并引入 `deepseek-spring-boot-starter` 依赖项以便于简化与 DeepSeek 平台之间的交互过程: ```xml <dependency> <groupId>com.deepseek</groupId> <artifactId>deepseek-spring-boot-starter</artifactId> <version>x.x.x</version> </dependency> ``` 接着,在项目的资源目录下编辑 `application.yml` 文件以指定连接到 DeepSeek 所必需的各项参数,例如基础 URL 及 API 密钥等信息[^2]: ```yaml spring: ai: openai: base-url: https://api.deepseek.com api-key: sk-xxxxxxxxxxxxxxxxx chat: options: model: deepseek-chat server: port: 8080 logging: level: cn.com.codingce.deepseek: DEBUG org.springframework.web: INFO ``` 对于更复杂的场景,可能还需要进一步调整其他属性,比如 WebFlux 设置或日志级别控制等内容[^3]。 #### 3. 构建 RESTful 接口 定义用于处理来自前端请求的服务端控制器类,通过调用封装好的客户端方法向 DeepSeek 发送消息并接收响应数据。下面给出了一段简单的代码片段作为参考: ```java @RestController @RequestMapping("/chat") public class ChatController { @Autowired private AiService aiService; @PostMapping("/message") public ResponseEntity<String> sendMessage(@RequestBody String message){ try { // 使用AiService发送消息给DeepSeek并获得回复 String response = aiService.sendMessage(message); return new ResponseEntity<>(response, HttpStatus.OK); } catch (Exception e) { return new ResponseEntity<>("Error occurred", HttpStatus.INTERNAL_SERVER_ERROR); } } } ``` 此部分逻辑可以根据实际需求灵活修改,如支持更多类型的输入输出格式或是加入异常捕获机制提高系统的健壮性。 #### 4. 前端开发(Vue) 在 Vue 中可以通过 Axios 库发起 HTTP 请求至上述构建的服务接口来进行聊天互动操作。首先需要安装 axios 插件: ```bash npm install --save axios ``` 之后可以在组件内部编写如下所示的方法用来触发 POST 请求并将用户输入的内容传递过去等待服务器返回结果后再显示出来: ```javascript import axios from &#39;axios&#39;; export default { data() { return { userInput: &#39;&#39;, messages: [] }; }, methods: { async submitMessage() { const res = await axios.post(&#39;http://localhost:8080/chat/message&#39;, this.userInput); this.messages.push({ text: this.userInput }); this.messages.push({ text: res.data }); this.userInput = &#39;&#39;; } } }; ``` 以上即完成了整个流程的设计说明,当然具体实施过程中可能会遇到各种各样的挑战,建议开发者们多查阅相关资料学习最佳实践案例从而更好地解决问题。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

后端码匠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值