面试题答案
一键面试1. 缓存策略
- 页面缓存:在Express中可使用
express - cache - response
中间件。安装后,在路由处使用,如:
const express = require('express');
const cache = require('express - cache - response');
const app = express();
app.get('/cached - route', cache({
duration: 60 * 1000, // 缓存60秒
etag: true
}), (req, res) => {
res.send('This is a cached response');
});
- 数据缓存:使用
node - cache
库。先安装,然后在应用中:
const NodeCache = require('node - cache');
const myCache = new NodeCache();
app.get('/data - route', (req, res) => {
const cachedData = myCache.get('my - data - key');
if (cachedData) {
return res.send(cachedData);
}
// 从数据库或其他地方获取数据
const newData = 'Some data from source';
myCache.set('my - data - key', newData);
res.send(newData);
});
2. 资源压缩
- 使用
compression
中间件:这是一个内置压缩功能的Express中间件。安装后在应用入口处使用:
const express = require('express');
const compression = require('compression');
const app = express();
app.use(compression());
// 后续路由等定义
此中间件会自动对响应进行gzip或deflate压缩,减少数据传输量。
3. 数据库连接池
- 对于MySQL:使用
mysql2
库并结合连接池。先安装mysql2
,然后:
const mysql = require('mysql2');
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'password',
database: 'test',
connectionLimit: 10 // 连接池最大连接数
});
const promisePool = pool.promise();
app.get('/db - query', async (req, res) => {
try {
const [rows] = await promisePool.query('SELECT * FROM your_table');
res.send(rows);
} catch (error) {
res.status(500).send('Database error');
}
});
- 对于MongoDB:使用
mongodb
官方驱动并配置连接池。安装后:
const { MongoClient } = require('mongodb');
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
poolSize: 10 // 连接池大小
});
async function connectDB() {
try {
await client.connect();
console.log('Connected to MongoDB');
return client.db('your - database');
} catch (error) {
console.error('Error connecting to MongoDB:', error);
}
}
const dbPromise = connectDB();
app.get('/mongodb - query', async (req, res) => {
const db = await dbPromise;
try {
const result = await db.collection('your - collection').find({}).toArray();
res.send(result);
} catch (error) {
res.status(500).send('MongoDB error');
}
});
4. 优化路由处理
- 中间件模块化:将复杂的路由逻辑拆分成多个中间件函数。例如,对于用户相关路由:
const express = require('express');
const router = express.Router();
function validateUser(req, res, next) {
// 用户验证逻辑
next();
}
function getUserData(req, res, next) {
// 获取用户数据逻辑
next();
}
router.get('/user', validateUser, getUserData, (req, res) => {
res.send('User data');
});
module.exports = router;
- 减少不必要的中间件:确保每个中间件都对请求处理有实际作用,避免引入过多无意义的中间件增加处理时间。
5. 异步处理优化
- 使用
async/await
:确保所有异步操作(如数据库查询、文件读取等)使用async/await
语法,让代码更简洁易读且利于错误处理。例如:
app.get('/async - route', async (req, res) => {
try {
const data = await someAsyncFunction();
res.send(data);
} catch (error) {
res.status(500).send('Async operation error');
}
});
- 并发处理:对于多个独立的异步操作,可以使用
Promise.all
来并发执行,减少总处理时间。例如:
app.get('/parallel - async - route', async (req, res) => {
const promise1 = someAsyncFunction1();
const promise2 = someAsyncFunction2();
try {
const [result1, result2] = await Promise.all([promise1, promise2]);
res.send({ result1, result2 });
} catch (error) {
res.status(500).send('Parallel async operation error');
}
});