构建智能导购商城:Spring Boot + Vue 3 + AI 导购实战

项目简介

Smart Shop 是一个基于 Spring Boot 3.2 + Vue 3 构建的智能导购商城系统,集成了 AI 大语言模型提供智能商品推荐服务。项目采用前后端分离架构,具备完整的商品管理、用户认证、购物车、订单等核心电商功能。

技术栈概览

后端技术

技术 版本 用途
Java 21 编程语言
Spring Boot 3.2.0 应用框架
MyBatis 3.0.3 ORM 框架
H2 2.x 内存数据库(开发环境)
MySQL 8.0+ 关系型数据库(生产环境)
Ollama 1.x 本地大模型运行时

前端技术

技术 版本 用途
Vue 3.4+ 前端框架
Vue Router 4.3+ 路由管理
Element Plus 2.6+ UI 组件库
Axios 1.6+ HTTP 请求

核心功能模块

1. 商品管理

商品模块提供完整的 CRUD 操作,支持按分类浏览和关键词搜索:

// ProductController.java - 商品搜索接口
@GetMapping("/search")
public ResponseEntity<List<Product>> searchProducts(@RequestParam String keyword) {
    return ResponseEntity.ok(productService.searchProducts(keyword));
}

2. 用户认证

实现了用户注册和登录功能,使用 Spring Boot 标准的 RESTful 接口设计:

// UserController.java
@PostMapping("/login")
public ResponseEntity<Map<String, Object>> login(@RequestBody User user) {
    User found = userService.login(user.getUsername(), user.getPassword());
    // ... 登录逻辑
}

3. 购物车管理

购物车支持添加商品、修改数量、删除商品等操作,数据持久化到数据库:

// CartController.java
@PostMapping
public ResponseEntity<Void> addToCart(@RequestBody Map<String, Object> request) {
    Long userId = ((Number) request.get("userId")).longValue();
    Long productId = ((Number) request.get("productId")).longValue();
    Integer quantity = (Integer) request.getOrDefault("quantity", 1);
    cartService.addToCart(userId, productId, quantity);
    return ResponseEntity.ok().build();
}

4. 订单管理

订单模块实现了从创建订单到订单状态跟踪的完整流程:

// OrderController.java
@PostMapping
public ResponseEntity<Order> createOrder(@RequestBody Map<String, Object> request) {
    Long userId = ((Number) request.get("userId")).longValue();
    List<Long> cartIds = ((List<?>) request.get("cartIds"))
            .stream().map(o -> ((Number) o).longValue()).toList();
    String shippingAddress = (String) request.get("shippingAddress");
    Order order = orderService.createOrder(userId, cartIds, shippingAddress);
    return ResponseEntity.ok(order);
}

5. AI 智能导购(核心亮点)

项目最具特色的功能是集成了本地大语言模型提供智能导购服务。通过 SSE(Server-Sent Events)实现流式响应,提供流畅的对话体验。

后端实现
// ChatService.java - 流式聊天核心逻辑
public void chatStream(String userMessage, OutputStream outputStream) {
    // 1. 获取商品目录
    List<Product> products = productService.getAllProducts();
    StringBuilder catalog = new StringBuilder();
    catalog.append("你是一个智能导购助手,帮助用户了解商城中的商品并给出推荐。\n");
    for (Product p : products) {
        catalog.append("- [").append(p.getId()).append("] ")
               .append(p.getName()).append(" | ¥").append(p.getPrice())
               .append(" | 分类:").append(p.getCategory()).append("\n");
    }
    
    // 2. 构建请求体
    Map<String, Object> requestBody = Map.of(
        "model", "deepseek-r1:7b",
        "stream", true,
        "messages", List.of(
            Map.of("role", "system", "content", catalog.toString()),
            Map.of("role", "user", "content", userMessage)
        )
    );
    
    // 3. 发送请求并处理流式响应
    // ... HTTP 请求和流式解析逻辑
}
SSE 控制器设计
// ChatController.java
@PostMapping
public DeferredResult<Void> chatStream(@RequestBody Map<String, String> request, 
                                        HttpServletResponse response) {
    response.setContentType("text/event-stream");
    response.setCharacterEncoding("UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Connection", "keep-alive");
    
    DeferredResult<Void> result = new DeferredResult<>(600000L);
    
    executor.execute(() -> {
        try {
            OutputStream os = response.getOutputStream();
            chatService.chatStream(message, os);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            result.setResult(null);
        }
    });
    
    return result;
}

数据库设计

项目使用关系型数据库,包含以下核心表:

-- 用户表
CREATE TABLE users (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL UNIQUE,
    password VARCHAR(100) NOT NULL,
    email VARCHAR(100) NOT NULL UNIQUE,
    -- ...
);

-- 商品表
CREATE TABLE products (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(200) NOT NULL,
    description TEXT,
    price DECIMAL(10, 2) NOT NULL,
    stock INT NOT NULL DEFAULT 0,
    category VARCHAR(50),
    sales_count INT DEFAULT 0,
    -- ...
);

-- 购物车表
CREATE TABLE cart (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    user_id BIGINT NOT NULL,
    product_id BIGINT NOT NULL,
    quantity INT NOT NULL DEFAULT 1,
    FOREIGN KEY (user_id) REFERENCES users(id),
    FOREIGN KEY (product_id) REFERENCES products(id)
);

-- 订单表
CREATE TABLE orders (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    user_id BIGINT NOT NULL,
    order_no VARCHAR(50) NOT NULL UNIQUE,
    total_amount DECIMAL(10, 2) NOT NULL,
    status VARCHAR(20) DEFAULT 'PENDING',
    -- ...
);

-- 订单项表
CREATE TABLE order_items (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    order_id BIGINT NOT NULL,
    product_id BIGINT NOT NULL,
    product_name VARCHAR(200) NOT NULL,
    price DECIMAL(10, 2) NOT NULL,
    quantity INT NOT NULL DEFAULT 1,
    FOREIGN KEY (order_id) REFERENCES orders(id)
);

前端架构

API 封装

// api/index.js
import axios from 'axios'

const API_BASE_URL = '/api'

const api = axios.create({
  baseURL: API_BASE_URL,
  headers: { 'Content-Type': 'application/json' }
})

export const productAPI = {
  getAll: () => api.get('/products'),
  getById: (id) => api.get(`/products/${id}`),
  getByCategory: (category) => api.get(`/products/category/${category}`),
  search: (keyword) => api.get(`/products/search?keyword=${keyword}`),
  getTopSellers: () => api.get('/products/top-sellers')
}

export const cartAPI = {
  getByUserId: (userId) => api.get(`/cart/${userId}`),
  add: (data) => api.post('/cart', data),
  update: (cartId, quantity) => api.put(`/cart/${cartId}`, { quantity }),
  remove: (cartId) => api.delete(`/cart/${cartId}`)
}

页面组件

页面 组件路径 功能
首页 views/Home.vue 商品展示、热销推荐
商品列表 views/ProductList.vue 分类筛选、搜索
商品详情 views/ProductDetail.vue 商品详情、加入购物车
购物车 views/Cart.vue 购物车管理、结算
订单 views/Orders.vue 订单列表、订单详情
登录/注册 views/Login.vue / Register.vue 用户认证
智能导购 views/Chat.vue AI 聊天界面

快速开始

1. 启动后端服务

cd backend
mvnw.cmd clean spring-boot:run

后端服务将在 http://localhost:8080 启动,H2 内存数据库会自动创建并初始化数据。

2. 启动前端服务

cd frontend
npm install
npm run dev

前端服务将在 http://localhost:8081 启动。

3. 启动 AI 导购服务(可选)

ollama run deepseek-r1:7b

启动 Ollama 并运行 deepseek-r1:7b 模型,即可使用智能导购功能。

测试账户

用户名: admin    密码: admin123
用户名: user1    密码: user123
用户名: user2    密码: user456

架构设计亮点

1. 前后端分离

采用标准的 RESTful API 设计,前后端完全解耦,便于团队协作和独立部署。

2. 流式 AI 响应

使用 SSE(Server-Sent Events)实现 AI 对话的流式响应,相比传统的轮询方式,大幅提升了用户体验。

3. 本地大模型集成

通过 Ollama 集成本地大语言模型,数据不出本地,保证了隐私安全,同时降低了 API 调用成本。

4. 多数据库支持

默认使用 H2 内存数据库,方便开发测试;生产环境可无缝切换到 MySQL。

5. MyBatis 持久层

使用 MyBatis 作为 ORM 框架,提供了灵活的 SQL 编写能力,同时支持 XML 映射和接口注解两种方式。

项目结构

Shop_test/
├── backend/                    # Spring Boot 后端
│   ├── src/main/java/com/example/smartshop/
│   │   ├── controller/        # REST API 控制器
│   │   ├── service/           # 业务逻辑层
│   │   ├── mapper/            # MyBatis 映射接口
│   │   ├── entity/            # 实体类
│   │   ├── config/            # 配置类
│   │   └── SmartShopApplication.java
│   └── src/main/resources/
│       ├── mapper/            # MyBatis XML 映射文件
│       ├── application.yml    # 应用配置
│       ├── schema.sql         # 数据库建表脚本
│       └── data.sql           # 初始数据
└── frontend/                   # Vue 前端
    ├── src/
    │   ├── views/             # 页面组件
    │   ├── components/        # 公共组件
    │   ├── router/            # 路由配置
    │   ├── api/               # API 封装
    │   ├── App.vue
    │   └── main.js
    └── package.json

总结

Smart Shop 智能导购商城项目展示了现代 Web 开发的最佳实践:

  1. 技术选型合理:Spring Boot 3.2 + Vue 3 是当前最主流的前后端技术组合
  2. 功能完整:涵盖电商系统的核心功能模块
  3. AI 赋能:集成本地大模型提供智能导购服务,是项目的核心亮点
  4. 易于上手:配置简单,启动快捷,适合学习和二次开发

如果你正在学习 Spring Boot 或 Vue 3,这个项目是一个很好的实践案例。你可以从项目中学习到前后端分离架构、RESTful API 设计、数据库操作、AI 集成等多个方面的知识。

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐