global.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package global
  2. import (
  3. "fmt"
  4. "hongze/hongqi_watch/config"
  5. "hongze/hongqi_watch/utils"
  6. "io"
  7. "github.com/fsnotify/fsnotify"
  8. "github.com/go-redis/redis/v8"
  9. "github.com/olivere/elastic/v7"
  10. oplogging "github.com/op/go-logging"
  11. "github.com/spf13/viper"
  12. "gorm.io/gorm"
  13. "github.com/rdlucklib/rdluck_tools/cache"
  14. )
  15. var (
  16. CONFIG config.Config //配置文件
  17. LOG *oplogging.Logger
  18. MYSQL map[string]*gorm.DB //数据库连接配置
  19. MYSQL_LOG io.Writer
  20. DEFAULT_MYSQL *gorm.DB //默认数据库连接配置
  21. Redis *redis.Client //redis链接
  22. EsClient *elastic.Client
  23. Rc *cache.Cache //redis缓存
  24. Re error //redis错误
  25. )
  26. const ConfigFile = "config/config_debug.yaml" //本地(测试)环境下的配置文件地址
  27. const ProConfigFile = "config/config.yaml" //生产环境下的配置文件地址
  28. func init() {
  29. v := viper.New()
  30. configFilePath := ConfigFile
  31. //如果不存在该配置文件,那么应该是线上环境,那么去寻找线上配置文件的路径
  32. if !utils.FileIsExist(configFilePath) {
  33. configFilePath = ProConfigFile
  34. }
  35. fmt.Println("configFilePath->", configFilePath)
  36. //设置配置文件
  37. v.SetConfigFile(configFilePath)
  38. err := v.ReadInConfig()
  39. if err != nil {
  40. panic(fmt.Errorf("读取配置失败,Err: %s \n", err))
  41. }
  42. //持续监听文件
  43. v.WatchConfig()
  44. v.OnConfigChange(func(e fsnotify.Event) {
  45. fmt.Println("配置文件变更:", e.Name)
  46. if err := v.Unmarshal(&CONFIG); err != nil {
  47. fmt.Println("配置重赋值失败,Err:", err)
  48. }
  49. fmt.Println(CONFIG)
  50. })
  51. if err := v.Unmarshal(&CONFIG); err != nil {
  52. fmt.Println("配置初始化赋值失败,Err:", err)
  53. }
  54. }