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

发布于:2025-08-05 ⋅ 阅读:(11) ⋅ 点赞:(0)

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


一、项目初始化

1. 创建项目目录
mkdir my-project
cd my-project
npm init -y
2. 安装基础依赖
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)
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)
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)
MYSQL_HOST=localhost
MYSQL_USER=root
MYSQL_PASSWORD=yourpassword
MYSQL_DATABASE=myapp
REDIS_HOST=localhost
PORT=3000

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

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)
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)
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)
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)
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. 使用示例(改造控制器)
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表
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 基础命令验证
redis-cli
> PING  # 应返回 "PONG"

七、项目运行与调试

1. 开发模式启动
npx nodemon app.js
2. 测试API
# 创建用户
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 进程管理
npm install -g pm2
pm2 start app.js --name "my-api"
2. 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设置密码认证

九、性能监控(可选)

npm install express-status-monitor

app.js 中添加:

const monitor = require('express-status-monitor');
app.use(monitor());

访问 /status 查看实时指标


通过以上流程,您已经构建了一个具备以下特性的生产级项目:
✅ RESTful API 基础架构
✅ MySQL 数据持久化
✅ Redis 缓存加速
✅ 分层架构设计(Router-Controller-Model)
✅ 环境变量管理
✅ 生产环境部署方案

可根据需求进一步扩展:

  • 添加JWT认证
  • 集成Swagger文档
  • 实现分页查询
  • 接入日志系统(Winston/Morgan)