config.go 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package performance_setting
  2. import (
  3. "github.com/QuantumNous/new-api/common"
  4. "github.com/QuantumNous/new-api/setting/config"
  5. )
  6. // PerformanceSetting 性能设置配置
  7. type PerformanceSetting struct {
  8. // DiskCacheEnabled 是否启用磁盘缓存(磁盘换内存)
  9. DiskCacheEnabled bool `json:"disk_cache_enabled"`
  10. // DiskCacheThresholdMB 触发磁盘缓存的请求体大小阈值(MB)
  11. DiskCacheThresholdMB int `json:"disk_cache_threshold_mb"`
  12. // DiskCacheMaxSizeMB 磁盘缓存最大总大小(MB)
  13. DiskCacheMaxSizeMB int `json:"disk_cache_max_size_mb"`
  14. // DiskCachePath 磁盘缓存目录
  15. DiskCachePath string `json:"disk_cache_path"`
  16. // MonitorEnabled 是否启用性能监控
  17. MonitorEnabled bool `json:"monitor_enabled"`
  18. // MonitorCPUThreshold CPU 使用率阈值(%)
  19. MonitorCPUThreshold int `json:"monitor_cpu_threshold"`
  20. // MonitorMemoryThreshold 内存使用率阈值(%)
  21. MonitorMemoryThreshold int `json:"monitor_memory_threshold"`
  22. // MonitorDiskThreshold 磁盘使用率阈值(%)
  23. MonitorDiskThreshold int `json:"monitor_disk_threshold"`
  24. }
  25. // 默认配置
  26. var performanceSetting = PerformanceSetting{
  27. DiskCacheEnabled: false,
  28. DiskCacheThresholdMB: 10, // 超过 10MB 使用磁盘缓存
  29. DiskCacheMaxSizeMB: 1024, // 最大 1GB 磁盘缓存
  30. DiskCachePath: "", // 空表示使用系统临时目录
  31. MonitorEnabled: true,
  32. MonitorCPUThreshold: 90,
  33. MonitorMemoryThreshold: 90,
  34. MonitorDiskThreshold: 90,
  35. }
  36. func init() {
  37. // 注册到全局配置管理器
  38. config.GlobalConfig.Register("performance_setting", &performanceSetting)
  39. // 同步初始配置到 common 包
  40. syncToCommon()
  41. }
  42. // syncToCommon 将配置同步到 common 包
  43. func syncToCommon() {
  44. common.SetDiskCacheConfig(common.DiskCacheConfig{
  45. Enabled: performanceSetting.DiskCacheEnabled,
  46. ThresholdMB: performanceSetting.DiskCacheThresholdMB,
  47. MaxSizeMB: performanceSetting.DiskCacheMaxSizeMB,
  48. Path: performanceSetting.DiskCachePath,
  49. })
  50. common.SetPerformanceMonitorConfig(common.PerformanceMonitorConfig{
  51. Enabled: performanceSetting.MonitorEnabled,
  52. CPUThreshold: performanceSetting.MonitorCPUThreshold,
  53. MemoryThreshold: performanceSetting.MonitorMemoryThreshold,
  54. DiskThreshold: performanceSetting.MonitorDiskThreshold,
  55. })
  56. }
  57. // GetPerformanceSetting 获取性能设置
  58. func GetPerformanceSetting() *PerformanceSetting {
  59. return &performanceSetting
  60. }
  61. // UpdateAndSync 更新配置并同步到 common 包
  62. // 当配置从数据库加载后,需要调用此函数同步
  63. func UpdateAndSync() {
  64. syncToCommon()
  65. }
  66. // GetCacheStats 获取缓存统计信息(代理到 common 包)
  67. func GetCacheStats() common.DiskCacheStats {
  68. return common.GetDiskCacheStats()
  69. }
  70. // ResetStats 重置统计信息
  71. func ResetStats() {
  72. common.ResetDiskCacheStats()
  73. }