You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
7.7 KiB
7.7 KiB
路由缓存系统
本项目实现了一个完整的路由缓存系统,包括路由匹配、控制器实例、中间件组合等多层缓存,可以显著提升应用性能。
功能特性
1. 多层缓存策略
- 路由匹配缓存: 缓存
method:path到路由对象的映射,避免重复的正则匹配 - 控制器实例缓存: 缓存控制器类实例,避免重复创建对象
- 中间件组合缓存: 缓存中间件组合结果,减少重复的函数组合操作
- 路由注册缓存: 缓存控制器文件的路由注册结果,支持文件变更检测
2. 智能缓存管理
- LRU淘汰策略: 自动清理最久未使用的缓存条目
- 文件变更检测: 基于文件修改时间的缓存失效机制
- 开发环境友好: 开发环境默认禁用缓存,生产环境自动启用
3. 性能监控
- 实时性能统计: 监控路由响应时间和缓存命中率
- 慢路由检测: 自动识别性能瓶颈路由
- 健康状态检查: 提供缓存系统健康度评估
配置说明
路由缓存和性能监控的配置已经完全抽离到通用配置系统中,支持环境变量和配置文件两种方式:
配置文件方式
在 src/config/index.js 中配置:
export default {
// 路由缓存配置
routeCache: {
enabled: process.env.NODE_ENV === 'production',
maxMatchCacheSize: 1000,
maxControllerCacheSize: 100,
maxMiddlewareCacheSize: 200,
maxRegistrationCacheSize: 50,
// 性能监控配置(旧版兼容)
performance: {
enabled: process.env.NODE_ENV === 'production',
windowSize: 100,
slowRouteThreshold: 500,
cleanupInterval: 5 * 60 * 1000
}
},
// 路由性能监控配置(独立配置)
routePerformance: {
// 基础配置
enabled: process.env.NODE_ENV === 'production' || process.env.PERFORMANCE_MONITOR === 'true',
windowSize: parseInt(process.env.PERFORMANCE_WINDOW_SIZE) || 100,
slowRouteThreshold: parseInt(process.env.SLOW_ROUTE_THRESHOLD) || 500,
cleanupInterval: parseInt(process.env.PERFORMANCE_CLEANUP_INTERVAL) || 5 * 60 * 1000,
// 高级配置
dataRetentionTime: parseInt(process.env.PERFORMANCE_DATA_RETENTION) || 10 * 60 * 1000,
minAnalysisDataCount: parseInt(process.env.MIN_ANALYSIS_DATA_COUNT) || 10,
cacheHitRateWarningThreshold: parseFloat(process.env.CACHE_HIT_RATE_WARNING) || 0.5,
enableOptimizationSuggestions: process.env.ENABLE_OPTIMIZATION_SUGGESTIONS !== 'false',
maxRouteReportCount: parseInt(process.env.MAX_ROUTE_REPORT_COUNT) || 50
}
}
环境变量方式
创建 .env 文件(参考 .env.example):
# 性能监控基础配置
PERFORMANCE_MONITOR=true
PERFORMANCE_WINDOW_SIZE=100
SLOW_ROUTE_THRESHOLD=500
# 高级配置
PERFORMANCE_CLEANUP_INTERVAL=300000
PERFORMANCE_DATA_RETENTION=600000
MIN_ANALYSIS_DATA_COUNT=10
CACHE_HIT_RATE_WARNING=0.5
ENABLE_OPTIMIZATION_SUGGESTIONS=true
MAX_ROUTE_REPORT_COUNT=50
API 接口
路由缓存系统提供了完整的管理 API:
缓存统计
# 获取缓存统计信息
GET /api/system/route-cache/stats
# 获取缓存健康状态
GET /api/system/route-cache/health
缓存清理
# 清除所有缓存
DELETE /api/system/route-cache/clear/all
# 清除路由匹配缓存
DELETE /api/system/route-cache/clear/routes
# 清除控制器实例缓存
DELETE /api/system/route-cache/clear/controllers
# 清除中间件组合缓存
DELETE /api/system/route-cache/clear/middlewares
# 清除路由注册缓存
DELETE /api/system/route-cache/clear/registrations
# 根据文件路径清除相关缓存
DELETE /api/system/route-cache/clear/file?filePath=/path/to/controller
缓存配置
# 更新缓存配置
PUT /api/system/route-cache/config
{
"enabled": true,
"maxMatchCacheSize": 2000
}
# 启用缓存
POST /api/system/route-cache/enable
# 禁用缓存
POST /api/system/route-cache/disable
使用示例
1. 基本使用
路由缓存已自动集成到路由系统中,无需额外配置:
// 控制器示例
export default class UserController extends BaseController {
async getUser(ctx) {
// 第一次访问会进行路由匹配并缓存
// 后续相同路径的请求将直接使用缓存
return this.success(ctx, user)
}
static createRoutes() {
const controller = new UserController()
const router = new Router({ prefix: '/api/users' })
router.get('/:id', controller.handleRequest(controller.getUser))
return router
}
}
2. 手动缓存管理
import routeCache from 'utils/cache/RouteCache.js'
// 获取缓存统计
const stats = routeCache.getStats()
console.log('缓存命中率:', stats.hitRate)
// 清除特定文件的缓存
routeCache.clearByFile('/path/to/controller.js')
// 禁用缓存(开发调试)
routeCache.disable()
3. 性能监控
import performanceMonitor from 'middlewares/RoutePerformance/index.js'
// 获取性能报告
const report = performanceMonitor.getPerformanceReport()
console.log('慢路由:', report.routes.filter(r => r.isSlowRoute))
// 获取慢路由列表
const slowRoutes = performanceMonitor.getSlowRoutes()
性能优化建议
1. 生产环境配置
// 生产环境建议配置
{
routeCache: {
enabled: true,
maxMatchCacheSize: 2000, // 增加缓存大小
maxControllerCacheSize: 200,
maxMiddlewareCacheSize: 500,
performance: {
enabled: true,
slowRouteThreshold: 300 // 降低慢路由阈值
}
}
}
2. 开发环境配置
// 开发环境建议配置
{
routeCache: {
enabled: false, // 禁用缓存以便调试
performance: {
enabled: true, // 保持性能监控
slowRouteThreshold: 1000
}
}
}
3. 缓存预热
// 应用启动时预热常用路由
const commonRoutes = [
{ method: 'GET', path: '/api/users' },
{ method: 'GET', path: '/api/articles' }
]
commonRoutes.forEach(route => {
// 模拟请求以预热缓存
// 实际实现可以在应用启动时发送内部请求
})
监控和调试
1. 日志输出
[路由缓存] 初始化完成,缓存状态: 启用
[路由注册] ✅ CommonController.js - 路由创建成功,已缓存
[路由缓存] 缓存状态: 启用, 总命中率: 87.3%
[性能监控] 发现慢路由: GET:/api/complex-query, 平均响应时间: 832.15ms, 缓存命中率: 23.5%
2. 健康检查
系统会自动检查:
- 缓存命中率是否过低
- 缓存大小是否过大
- 是否存在性能问题
3. 告警和优化建议
当检测到问题时,系统会提供优化建议:
- 调整缓存策略
- 增加缓存大小
- 优化慢路由逻辑
注意事项
- 内存使用: 缓存会占用内存,需要根据服务器资源调整缓存大小
- 开发调试: 开发环境建议禁用缓存以避免代码更改不生效
- 集群部署: 当前是内存缓存,集群部署时每个实例独立缓存
- 缓存失效: 文件变更会自动失效相关缓存,但手动修改需要重启应用
扩展功能
1. Redis 缓存适配
// 未来可以扩展为 Redis 缓存
class RedisRouteCache extends RouteCache {
// 实现 Redis 存储逻辑
}
2. 分布式缓存
// 支持集群间缓存同步
class DistributedRouteCache extends RouteCache {
// 实现分布式缓存逻辑
}
3. 更多性能指标
- 内存使用监控
- 缓存空间利用率
- 自动缓存优化算法