perf(数据库): 优化数据库查询性能

- 在设备、机柜路由中强制使用 JOIN 避免 N+1 查询问题
- 添加连接池配置提升并发处理能力
- 设置 distinct 和 subQuery 参数确保查询准确性
This commit is contained in:
zhang1106
2026-02-10 14:35:36 +08:00
parent 18c3a3eb15
commit b9d89bee11
3 changed files with 35 additions and 15 deletions
+16 -2
View File
@@ -17,7 +17,14 @@ if (DB_TYPE === 'mysql') {
host: process.env.MYSQL_HOST || 'localhost',
port: parseInt(process.env.MYSQL_PORT) || 3306,
dialect: 'mysql',
logging: process.env.NODE_ENV === 'development' ? console.log : false
logging: process.env.NODE_ENV === 'development' ? console.log : false,
// 连接池配置 - 提升并发处理能力
pool: {
max: 10, // 最大连接数
min: 2, // 最小连接数
acquire: 30000, // 获取连接超时时间(ms)
idle: 10000 // 连接空闲时间(ms)
}
}
);
dbDialect = 'mysql';
@@ -25,7 +32,14 @@ if (DB_TYPE === 'mysql') {
sequelize = new Sequelize({
dialect: 'sqlite',
storage: process.env.DB_PATH || './idc_management.db',
logging: process.env.NODE_ENV === 'development' ? console.log : false
logging: process.env.NODE_ENV === 'development' ? console.log : false,
// SQLite 连接池配置
pool: {
max: 5,
min: 1,
acquire: 30000,
idle: 10000
}
});
dbDialect = 'sqlite';
}
+6 -3
View File
@@ -98,7 +98,7 @@ router.get('/', validateQuery(queryDeviceSchema), async (req, res) => {
where.rackId = rackId;
}
// 执行查询
// 执行查询 - 优化:使用 JOIN 避免 N+1 查询问题
const { count, rows } = await Device.findAndCountAll({
where,
include: [
@@ -106,11 +106,14 @@ router.get('/', validateQuery(queryDeviceSchema), async (req, res) => {
model: Rack,
include: [
{ model: Room }
]
],
separate: false // 强制使用 JOIN 而不是单独查询
}
],
offset,
limit: parseInt(pageSize)
limit: parseInt(pageSize),
distinct: true, // 避免 count 不准确
subQuery: false // 避免子查询导致的性能问题
});
res.json({
+13 -10
View File
@@ -39,15 +39,16 @@ router.get('/', async (req, res) => {
// 获取总记录数(带筛选条件)
const total = await Rack.count({ where });
// 获取分页数据
// 获取分页数据 - 优化:使用 JOIN 避免 N+1 查询问题
const racks = await Rack.findAll({
where,
include: [
{ model: Room },
{ model: Device }
{ model: Room, separate: false },
{ model: Device, separate: false }
],
limit: pageSize,
offset: offset
offset: offset,
subQuery: false // 避免子查询导致的性能问题
});
// 返回带分页信息的响应
@@ -220,9 +221,10 @@ router.get('/:rackId', async (req, res) => {
try {
const rack = await Rack.findByPk(req.params.rackId, {
include: [
{ model: Room },
{ model: Device }
]
{ model: Room, separate: false },
{ model: Device, separate: false }
],
subQuery: false // 避免子查询导致的性能问题
});
if (!rack) {
return res.status(404).json({ error: '机柜不存在' });
@@ -286,9 +288,10 @@ router.put('/:rackId', validateBody(updateRackSchema), async (req, res) => {
if (updated) {
const updatedRack = await Rack.findByPk(req.params.rackId, {
include: [
{ model: Room },
{ model: Device }
]
{ model: Room, separate: false },
{ model: Device, separate: false }
],
subQuery: false // 避免子查询导致的性能问题
});
res.json(updatedRack);
} else {