Node.js (Express) + MySQL + Redis构建项目流程

以下是使用 Node.js (Express) + MySQL + Redis 构建完整项目的详细流程,涵盖环境搭建、架构设计、核心代码实现和部署优化:


一、项目初始化

1. 创建项目目录
bash 复制代码
mkdir my-project
cd my-project
npm init -y
2. 安装基础依赖
bash 复制代码
npm install express mysql2 redis dotenv cors
npm install --save-dev nodemon eslint prettier
3. 目录结构设计
复制代码
my-project/
├── config/               # 配置文件
│   ├── db.js            # 数据库连接
│   └── redis.js         # Redis连接
├── controllers/         # 业务逻辑
│   └── userController.js
├── models/              # 数据模型
│   └── User.js
├── routes/              # 路由定义
│   └── userRoutes.js
├── middlewares/         # 中间件
│   └── authMiddleware.js
├── utils/               # 工具函数
│   └── cache.js
├── app.js               # 应用入口
├── .env                 # 环境变量
└── package.json

二、数据库配置

1. MySQL 连接配置 (config/db.js)
javascript 复制代码
const mysql = require('mysql2/promise');
const pool = mysql.createPool({
  host: process.env.MYSQL_HOST,
  user: process.env.MYSQL_USER,
  password: process.env.MYSQL_PASSWORD,
  database: process.env.MYSQL_DATABASE,
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

module.exports = pool;
2. Redis 连接配置 (config/redis.js)
javascript 复制代码
const redis = require('redis');
const client = redis.createClient({
  url: `redis://${process.env.REDIS_HOST}:6379`
});

client.on('error', (err) => console.log('Redis Client Error', err));
client.connect();

module.exports = client;
3. 环境变量 (.env)
ini 复制代码
MYSQL_HOST=localhost
MYSQL_USER=root
MYSQL_PASSWORD=yourpassword
MYSQL_DATABASE=myapp
REDIS_HOST=localhost
PORT=3000

三、Express 应用骨架 (app.js)

javascript 复制代码
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const userRoutes = require('./routes/userRoutes');

const app = express();

// 中间件
app.use(cors());
app.use(express.json());

// 路由
app.use('/api/users', userRoutes);

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Server Error');
});

// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

四、核心功能实现

1. 数据模型 (models/User.js)
javascript 复制代码
const pool = require('../config/db');

class User {
  static async create({ username, email }) {
    const [result] = await pool.query(
      'INSERT INTO users (username, email) VALUES (?, ?)',
      [username, email]
    );
    return result.insertId;
  }

  static async findById(id) {
    const [rows] = await pool.query('SELECT * FROM users WHERE id = ?', [id]);
    return rows[0];
  }
}

module.exports = User;
2. 控制器 (controllers/userController.js)
javascript 复制代码
const User = require('../models/User');
const client = require('../config/redis');

const UserController = {
  async createUser(req, res) {
    try {
      const userId = await User.create(req.body);
      res.status(201).json({ id: userId });
    } catch (err) {
      res.status(500).json({ error: err.message });
    }
  },

  async getUser(req, res) {
    try {
      const { id } = req.params;
      const cacheKey = `user:${id}`;

      // 检查Redis缓存
      const cachedUser = await client.get(cacheKey);
      if (cachedUser) return res.json(JSON.parse(cachedUser));

      // 数据库查询
      const user = await User.findById(id);
      if (!user) return res.status(404).send('User not found');

      // 设置缓存(过期时间60秒)
      await client.setEx(cacheKey, 60, JSON.stringify(user));
      res.json(user);
    } catch (err) {
      res.status(500).json({ error: err.message });
    }
  }
};

module.exports = UserController;
3. 路由定义 (routes/userRoutes.js)
javascript 复制代码
const express = require('express');
const router = express.Router();
const UserController = require('../controllers/userController');

router.post('/', UserController.createUser);
router.get('/:id', UserController.getUser);

module.exports = router;

五、高级功能扩展

1. 缓存工具类 (utils/cache.js)
javascript 复制代码
const client = require('../config/redis');

const Cache = {
  async getOrSet(key, cb, ttl = 60) {
    const cachedData = await client.get(key);
    if (cachedData) return JSON.parse(cachedData);

    const freshData = await cb();
    await client.setEx(key, ttl, JSON.stringify(freshData));
    return freshData;
  }
};

module.exports = Cache;
2. 使用示例(改造控制器)
javascript 复制代码
const Cache = require('../utils/cache');

async getUser(req, res) {
  const { id } = req.params;
  const user = await Cache.getOrSet(
    `user:${id}`,
    () => User.findById(id),
    60 // TTL 60秒
  );
  res.json(user);
}

六、数据库初始化

1. 创建MySQL表
sql 复制代码
CREATE TABLE users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  username VARCHAR(50) NOT NULL,
  email VARCHAR(100) NOT NULL UNIQUE,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
2. Redis 基础命令验证
bash 复制代码
redis-cli
> PING  # 应返回 "PONG"

七、项目运行与调试

1. 开发模式启动
bash 复制代码
npx nodemon app.js
2. 测试API
bash 复制代码
# 创建用户
curl -X POST http://localhost:3000/api/users \
  -H "Content-Type: application/json" \
  -d '{"username":"test","email":"test@example.com"}'

# 查询用户
curl http://localhost:3000/api/users/1

八、生产环境部署

1. PM2 进程管理
bash 复制代码
npm install -g pm2
pm2 start app.js --name "my-api"
2. Nginx 反向代理配置
nginx 复制代码
server {
  listen 80;
  server_name api.example.com;

  location / {
    proxy_pass http://localhost:3000;
    proxy_set_header Host $host;
  }
}
3. 安全加固
  • 使用HTTPS(Let's Encrypt)
  • 数据库连接限制IP白名单
  • Redis设置密码认证

九、性能监控(可选)

bash 复制代码
npm install express-status-monitor

app.js 中添加:

javascript 复制代码
const monitor = require('express-status-monitor');
app.use(monitor());

访问 /status 查看实时指标


通过以上流程,您已经构建了一个具备以下特性的生产级项目:

✅ RESTful API 基础架构

✅ MySQL 数据持久化

✅ Redis 缓存加速

✅ 分层架构设计(Router-Controller-Model)

✅ 环境变量管理

✅ 生产环境部署方案

可根据需求进一步扩展:

  • 添加JWT认证
  • 集成Swagger文档
  • 实现分页查询
  • 接入日志系统(Winston/Morgan)
相关推荐
濮水大叔1 小时前
Prisma不能优雅的支持DTO,试试Vona ORM吧
前端框架·node.js·orm
WindrunnerMax4 小时前
浅谈 RAG 并基于 NodeJS 实现基础向量检索服务
架构·node.js·aigc
什么半岛铁盒4 小时前
MySQL 约束知识体系:八大约束类型详细讲解
android·数据库·mysql
香蕉可乐荷包蛋5 小时前
node.js常用函数
node.js
Lemon程序馆5 小时前
Mysql 常见的性能分析手段
数据库·后端·mysql
静西子6 小时前
mysql远程登陆失败
数据库·mysql
JAVA学习通6 小时前
【MySQL进阶】------MySQL程序
数据库·mysql
还是鼠鼠15 小时前
tlias智能学习辅助系统--SpringAOP-进阶-通知顺序
java·后端·mysql·spring·mybatis·springboot
飞翔的佩奇15 小时前
基于SpringBoot+MyBatis+MySQL+VUE实现的名城小区物业管理系统(附源码+数据库+毕业论文+开题报告+部署教程+配套软件)
数据库·vue.js·spring boot·mysql·毕业设计·mybatis·小区物业管理系统