global.go 1.5 KB

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