性能优化
本文介绍如何优化 API 调用性能和响应速度。
请求优化
批量查询
支持批量查询的接口,减少请求次数:
POST /v1/person/identity/batch-verify
{
"items": [
{ "name": "张三", "idCard": "110101199001011234" },
{ "name": "李四", "idCard": "110101199001011235" }
]
}
按需查询
只请求需要的数据字段:
POST /v1/enterprise/info?fields=basic,finance
连接复用
使用 HTTP Keep-Alive,复用 TCP 连接:
const axios = require('axios');
const client = axios.create({
baseURL: 'https://api.turningapi.com',
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true })
});
缓存策略
客户端缓存
对于变化不频繁的数据,在本地缓存:
const cache = new Map();
const CACHE_TTL = 3600 * 1000; // 1小时
async function queryWithCache(key, queryFn) {
const cached = cache.get(key);
if (cached && Date.now() - cached.time < CACHE_TTL) {
return cached.data;
}
const data = await queryFn();
cache.set(key, { data, time: Date.now() });
return data;
}
服务端缓存
部分接口支持服务端缓存,响应 Header 包含:
Cache-Control: max-age=3600ETag: "abc123"
并发控制
合理并发
控制并发请求数,避免触发限流:
const pLimit = require('p-limit');
const limit = pLimit(10); // 最多 10 个并发
const results = await Promise.all(
items.map(item => limit(() => api.query(item)))
);
限流处理
收到 429 响应时,使用指数退避重试:
async function retryWithBackoff(fn, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await fn();
} catch (error) {
if (error.status !== 429 || i === maxRetries - 1) throw error;
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
}
}
}
监控指标
建议监控以下指标:
- 请求响应时间 (P50, P95, P99)
- 错误率
- 限流触发次数