global.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package global
  2. import (
  3. "fmt"
  4. "github.com/fsnotify/fsnotify"
  5. "github.com/go-redis/redis/v8"
  6. oplogging "github.com/op/go-logging"
  7. "github.com/patrickmn/go-cache"
  8. "github.com/spf13/viper"
  9. "gorm.io/gorm"
  10. "hongze/hongtao3_watch/config"
  11. "hongze/hongtao3_watch/utils"
  12. "io"
  13. "io/fs"
  14. "os"
  15. "path/filepath"
  16. "syscall"
  17. "time"
  18. )
  19. var (
  20. CONFIG config.Config //配置文件
  21. LOG *oplogging.Logger
  22. MYSQL map[string]*gorm.DB //数据库连接配置
  23. MYSQL_LOG io.Writer
  24. DEFAULT_MYSQL *gorm.DB //默认数据库连接配置
  25. Redis *redis.Client //redis链接
  26. CacheClient *cache.Cache
  27. )
  28. const ConfigFile = "config/config_debug.yaml" //本地(测试)环境下的配置文件地址
  29. const ProConfigFile = "config/config.yaml" //生产环境下的配置文件地址
  30. func init() {
  31. v := viper.New()
  32. configFilePath := ConfigFile
  33. //如果不存在该配置文件,那么应该是线上环境,那么去寻找线上配置文件的路径
  34. if !utils.FileIsExist(configFilePath) {
  35. configFilePath = ProConfigFile
  36. }
  37. fmt.Println("configFilePath->", configFilePath)
  38. //设置配置文件
  39. v.SetConfigFile(configFilePath)
  40. err := v.ReadInConfig()
  41. if err != nil {
  42. panic(fmt.Errorf("读取配置失败,Err: %s \n", err))
  43. }
  44. //持续监听文件
  45. v.WatchConfig()
  46. v.OnConfigChange(func(e fsnotify.Event) {
  47. fmt.Println("配置文件变更:", e.Name)
  48. if err := v.Unmarshal(&CONFIG); err != nil {
  49. fmt.Println("配置重赋值失败,Err:", err)
  50. }
  51. fmt.Println(CONFIG)
  52. })
  53. if err := v.Unmarshal(&CONFIG); err != nil {
  54. fmt.Println("配置初始化赋值失败,Err:", err)
  55. }
  56. cache.New(365*24*time.Hour, 365*24*time.Hour)
  57. ReadDefaultFileModifyTime()
  58. }
  59. func ReadDefaultFileModifyTime() {
  60. CacheClient = cache.New(365*24*time.Hour, 365*24*time.Hour)
  61. err := filepath.Walk(CONFIG.Serve.ListenExcelPath, func(path string, info fs.FileInfo, err error) error {
  62. if err != nil {
  63. return err
  64. }
  65. if !info.IsDir() {
  66. fmt.Println(path)
  67. fileInfo, err := os.Stat(path)
  68. if err != nil {
  69. fmt.Println("os.Stat:", err.Error())
  70. }
  71. winFileAttr := fileInfo.Sys().(*syscall.Win32FileAttributeData)
  72. modifyTime := SecondToTime(winFileAttr.LastWriteTime.Nanoseconds() / 1e9).Format(utils.FormatDateTime)
  73. fmt.Println("最后修改时间:", modifyTime)
  74. CacheClient.Set(path, modifyTime, 24*time.Hour)
  75. }
  76. return nil
  77. })
  78. fmt.Println("Read err:", err)
  79. }
  80. // 把秒级的时间戳转为time格式
  81. func SecondToTime(sec int64) time.Time {
  82. return time.Unix(sec, 0)
  83. }