hot_reload.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package config
  2. import (
  3. "reflect"
  4. "sync"
  5. klog "github.com/sirupsen/logrus"
  6. )
  7. var (
  8. // lastConfigValues 记录上一次配置文件中的值,用于热更新时比较
  9. lastConfigValues map[string]interface{}
  10. lastConfigValuesMu sync.RWMutex
  11. )
  12. // initLastConfigValues 初始化 lastConfigValues(如果还未初始化)
  13. func initLastConfigValues() {
  14. lastConfigValuesMu.Lock()
  15. defer lastConfigValuesMu.Unlock()
  16. if lastConfigValues == nil {
  17. lastConfigValues = make(map[string]interface{})
  18. }
  19. }
  20. // getLastConfigValue 获取上一次配置文件中的值
  21. func getLastConfigValue(key string) (interface{}, bool) {
  22. lastConfigValuesMu.RLock()
  23. defer lastConfigValuesMu.RUnlock()
  24. val, ok := lastConfigValues[key]
  25. return val, ok
  26. }
  27. // setLastConfigValue 设置上一次配置文件中的值
  28. func setLastConfigValue(key string, value interface{}) {
  29. lastConfigValuesMu.Lock()
  30. defer lastConfigValuesMu.Unlock()
  31. if lastConfigValues == nil {
  32. lastConfigValues = make(map[string]interface{})
  33. }
  34. lastConfigValues[key] = value
  35. }
  36. // checkAndUpdateConfigValue 检查配置值是否改变,如果改变则执行更新操作
  37. // key: 配置项的键(如 "logging.log_level")
  38. // newValue: 配置文件中的新值
  39. // isHotReload: 是否为热更新
  40. // updateFunc: 如果值改变,需要执行的更新函数
  41. // 返回: 是否发生了改变
  42. func checkAndUpdateConfigValue(key string, newValue interface{}, isHotReload bool, updateFunc func()) bool {
  43. initLastConfigValues()
  44. if isHotReload {
  45. // 热更新:比较新值和上一次的值
  46. lastValue, hasLastValue := getLastConfigValue(key)
  47. if !hasLastValue || !valuesEqual(lastValue, newValue) {
  48. if hasLastValue {
  49. klog.Infof("🔄 [CONFIG] %s changed in config file: %v -> %v", key, lastValue, newValue)
  50. } else {
  51. klog.Infof("🔄 [CONFIG] %s first detected in config file: %v", key, newValue)
  52. }
  53. if updateFunc != nil {
  54. updateFunc()
  55. }
  56. setLastConfigValue(key, newValue)
  57. return true
  58. }
  59. return false
  60. } else {
  61. // 初始加载:记录初始值
  62. setLastConfigValue(key, newValue)
  63. if updateFunc != nil {
  64. updateFunc()
  65. }
  66. return true
  67. }
  68. }
  69. // valuesEqual 比较两个值是否相等(支持基本类型和字符串)
  70. func valuesEqual(a, b interface{}) bool {
  71. if a == nil && b == nil {
  72. return true
  73. }
  74. if a == nil || b == nil {
  75. return false
  76. }
  77. // 使用反射进行深度比较
  78. return reflect.DeepEqual(a, b)
  79. }