当前位置: 首页 > news >正文

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

以下是使用 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)
http://www.dtcms.com/a/312624.html

相关文章:

  • C++ 入门基础(3)
  • 从零开始学Express,理解服务器,路由于中间件
  • Ubuntu20.04 Carla安装与和Ros联合仿真
  • OpenCV轻松入门_面向python(第一章OpenCV入门)
  • Kafka——怎么重设消费者组位移?
  • 北京-4年功能测试2年空窗-报培训班学测开-第六十六天
  • 「iOS」————属性关键字底层原理
  • Jupyter Notebook 中高效处理和实时展示来自 OpenCV 和 Pillow 的图像数据探究
  • 网络缓冲区的设计以及C++实现
  • 【Python练习】075. 编写一个函数,实现简单的语音识别功能
  • 项目日记---高并发内存池整体框架
  • 人工智能与医疗健康:AI 助力医疗的新格局
  • 信号传播速度与延时
  • [硬件电路-143]:模拟电路 - 开关电源与线性稳压电源的详细比较
  • PLC传感器接线与输出信号接线
  • Redis实战(7)-- 高级特性 Redis Stream数据结构与基础命令
  • 【0基础PS】PS工具详解--文字工具
  • .NET 开源节点编辑器,将你的程序功能模块节点化
  • pytorch 安装
  • Paxos 算法是什么?介绍 RAFT 和 ZAB,以及它们之间的区别?会有脑裂问题吗?为什么?
  • 算法竞赛阶段二-数据结构(39)数据结构栈模拟实现
  • AI陪伴赛道,热闹背后是真需求还是泡沫?
  • 应急响应整理
  • Back to the Features:附录A
  • [创业之路-532]:知识、技能、技术、科学各自解决什么问题?
  • 手机(电脑)与音响的蓝牙通信
  • 15_01_opencv_形态学滤波
  • 动态置信度调优实战:YOLOv11多目标追踪精度跃迁方案(附完整代码)
  • C++引用:高效安全的别名机制详解
  • 用于 UBI 的 Elasticsearch 插件:从搜索查询中分析用户行为