app.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. package config
  2. import (
  3. "crypto/rsa"
  4. "crypto/tls"
  5. "fmt"
  6. "os"
  7. "strings"
  8. "sync"
  9. "time"
  10. "gitee.com/xuyiping_admin/pkg/di"
  11. )
  12. var (
  13. Module = di.Provide(Options)
  14. options *AppConfig
  15. appEnv string
  16. initOnce sync.Once
  17. )
  18. // AppConfig store all configuration options
  19. type AppConfig struct {
  20. FarmName string `yaml:"farm_name"`
  21. AppName string `yaml:"app_name"`
  22. AppEnv string `yaml:"app_environment"`
  23. Debug bool `yaml:"debug"`
  24. HTTPServerAddr string `yaml:"http_server_addr"`
  25. NeckRingLimit int32 `yaml:"neck_ring_limit"`
  26. // 数据库配置 额外加载文件部分 database.yaml
  27. StoreSetting StoreSetting `json:"storeSetting" yaml:"store"`
  28. // redis 配置
  29. RedisSetting RedisSetting `json:"RedisSetting" yaml:"redis_setting"`
  30. JwtSecret string `json:"jwtSecret" yaml:"jwt_secret"`
  31. ExcelSetting ExcelSetting `json:"excelSetting" yaml:"excel_setting"`
  32. WechatSetting WechatSetting `json:"wechatSetting" yaml:"wechat_setting"`
  33. JwtTokenKeyConfig JwtTokenKeyConfig `json:"jwtTokenKeyConfig"`
  34. JwtExpireTime int `json:"jwtExpireTime" yaml:"jwt_expire_time"`
  35. // asynq 相关配置
  36. SideWorkSetting SideWorkSetting `yaml:"side_work_setting"`
  37. CronSetting CronSetting `json:"cron_setting" yaml:"cron"`
  38. Mqtt MqttSetting `json:"mqtt"`
  39. }
  40. type CronSetting struct {
  41. // 是否启动任务时先跑一次
  42. CrontabStartRun bool `yaml:"crontab_start_run"`
  43. // CRONTAB 表达式
  44. UpdateCowInfo string `yaml:"update_cow_info"` // 更新牛只信息
  45. GenerateWorkOrder string `yaml:"generate_work_order"` // 生成工作单
  46. ImmunizationPlan string `yaml:"immunization_plan"` // 免疫计划
  47. SameTimePlan string `yaml:"same_time_plan"` // 同期
  48. UpdateSameTime string `yaml:"update_same_time"` // 更新同期
  49. SystemBasicCrontab string `yaml:"system_basic_crontab"` // 系统基础定时任务
  50. CowPregnant string `yaml:"cow_pregnant"` // 月度牛只怀孕清单
  51. UpdateActiveHabit string `yaml:"update_active_habit"` // 脖环2小时数据重新整合
  52. NeckRingEstrus string `yaml:"neck_ring_estrus"` // 脖环牛只发情
  53. NeckRingMerge string `yaml:"neck_ring_merge"` // 脖环原始数据合并
  54. NeckRingCalculate string `yaml:"neck_ring_calculate"` // 脖环数据计算
  55. }
  56. type JwtTokenKeyConfig struct {
  57. PrivateKey *rsa.PrivateKey `json:"privateKey"`
  58. PublicKey *rsa.PublicKey `json:"publicKey"`
  59. }
  60. type WechatSetting struct {
  61. Appid string `yaml:"appid"`
  62. Secret string `yaml:"secret"`
  63. }
  64. type ExcelSetting struct {
  65. SheetName string `yaml:"sheet_name"` // = "Sheet1" //默认Sheet名称
  66. Height float64 `yaml:"height"` // = 25.0 //默认行高度
  67. }
  68. // StoreSetting 数据库配置
  69. type StoreSetting struct {
  70. // 开启 SyDb SQL 记录
  71. DriverName string `yaml:"driver_name" json:"driver_name"`
  72. ShowSQL bool `yaml:"show_sql" json:"show_sql"`
  73. KptRW string `yaml:"kpt_rw" json:"kpt_rw"`
  74. KptMigr string `yaml:"kpt_migr" json:"kpt_migr"`
  75. KptMqtt string `yaml:"kpt_mqtt" json:"kpt_mqtt"`
  76. }
  77. type RedisSetting struct {
  78. // sso 配置
  79. CacheRedis CacheRedisDB `json:"cache_redis" yaml:"cache_redis"`
  80. }
  81. type CacheRedisDB struct {
  82. Addr string `json:"addr" yaml:"addr"`
  83. DB int `json:"db" yaml:"db"`
  84. Requirepass string `json:"requirepass" yaml:"requirepass"`
  85. Expiry int `json:"expiry" yaml:"expiry"`
  86. }
  87. type SideWorkSetting struct {
  88. // Asynq 配置
  89. AsynqSetting AsynqSetting `json:"asynq_setting,omitempty" yaml:"asynq_setting"`
  90. }
  91. type AsynqSetting struct {
  92. Redis AsynqRedisSetting `json:"redis" yaml:"redis"`
  93. Queues map[string]int `json:"queues,omitempty" yaml:"queues"`
  94. Concurrency int `json:"concurrency,omitempty" yaml:"concurrency"`
  95. LogLevel int32 `json:"log_level,omitempty" yaml:"log_level"`
  96. }
  97. type AsynqRedisSetting struct {
  98. // Network type to use, either tcp or unix.
  99. // Default is tcp.
  100. Network string `json:"network,omitempty" yaml:"network"`
  101. // Redis server address in "host:port" format.
  102. Addr string `json:"addr,omitempty" yaml:"addr"`
  103. // Username to authenticate the current connection when Redis ACLs are used.
  104. // See: https://redis.io/commands/auth.
  105. Username string `json:"username,omitempty" yaml:"username"`
  106. // Password to authenticate the current connection.
  107. // See: https://redis.io/commands/auth.
  108. Password string `json:"password,omitempty" yaml:"password"`
  109. // Redis DB to select after connecting to a server.
  110. // See: https://redis.io/commands/select.
  111. DB int `json:"db,omitempty" yaml:"db"`
  112. // Dial timeout for establishing new connections.
  113. // Default is 5 seconds.
  114. DialTimeout time.Duration `json:"dialTimeout,omitempty" yaml:"dial_timeout"`
  115. // Timeout for socket reads.
  116. // If timeout is reached, read commands will fail with a timeout error
  117. // instead of blocking.
  118. //
  119. // Use value -1 for no timeout and 0 for default.
  120. // Default is 3 seconds.
  121. ReadTimeout time.Duration `json:"readTimeout,omitempty" yaml:"read_timeout"`
  122. // Timeout for socket writes.
  123. // If timeout is reached, write commands will fail with a timeout error
  124. // instead of blocking.
  125. //
  126. // Use value -1 for no timeout and 0 for default.
  127. // Default is ReadTimout.
  128. WriteTimeout time.Duration `json:"writeTimeout,omitempty" yaml:"write_timeout"`
  129. // Maximum number of socket connections.
  130. // Default is 10 connections per every CPU as reported by runtime.NumCPU.
  131. PoolSize int `json:"poolSize,omitempty" yaml:"pool_size"`
  132. // TLS Config used to connect to a server.
  133. // TLS will be negotiated only if this field is set.
  134. TLSConfig *tls.Config `json:"tlsConfig,omitempty" yaml:"tls_config"`
  135. }
  136. type MqttSetting struct {
  137. Broker string `json:"broker" yaml:"broker"`
  138. UserName string `json:"username" yaml:"username"`
  139. Password string `json:"password" yaml:"password"`
  140. SubTopic string `json:"sub_topic" yaml:"sub_topic"`
  141. Retain bool `json:"retain" yaml:"retain"`
  142. Qos int `json:"qos" yaml:"qos"`
  143. KeepAlive int `json:"keepAlive" yaml:"keep_alive"`
  144. ConnectTimeout int `json:"connectTimeout" yaml:"connect_timeout"`
  145. AutoReconnect bool `json:"autoReconnect" yaml:"auto_reconnect"`
  146. ReconnectInterval int `json:"reconnectInterval" yaml:"reconnect_interval"`
  147. WorkNumber int `json:"workNumber" yaml:"work_number"`
  148. MergeDataTicker int `json:"mergeDataTicker" yaml:"merge_data_ticker"`
  149. }
  150. func (a *AppConfig) Name() string {
  151. return fmt.Sprintf("%s-%s", a.AppName, a.AppEnv)
  152. }
  153. // CacheNameSpace 作为 Key 的前缀,用来区分不同环境,不同 APP 下的 Key,防止缓存干扰
  154. // 踩坑记录:
  155. //
  156. // 如果使用 fmt.Sprintf("%s-%s-%s", a.AppName, a.AppRole, a.AppEnv),例如 sayam-http-production, sayam-consumer-production
  157. // 会导致 从 role http 写入的 key,从 role consumer 中取不出来,反之亦然
  158. // 支持更多的key空间, 可以更灵活的定义ns
  159. func (a *AppConfig) CacheNameSpace() string {
  160. cacheKeySpace := ""
  161. if a.FarmName != "" {
  162. cacheKeySpace = fmt.Sprintf("%s-%s-%s", a.AppName, a.AppEnv, a.FarmName)
  163. } else {
  164. cacheKeySpace = fmt.Sprintf("%s-%s", a.AppName, a.AppEnv)
  165. }
  166. return cacheKeySpace
  167. }
  168. func Options() *AppConfig {
  169. return options
  170. }
  171. func init() {
  172. appEnv = strings.ToLower(os.Getenv("APP_ENVIRONMENT"))
  173. cfg := &AppConfig{}
  174. var err error
  175. initOnce.Do(func() {
  176. switch appEnv {
  177. case "test":
  178. err = Initialize("app.test.yaml", cfg)
  179. case "development":
  180. err = Initialize("app.develop.yaml", cfg)
  181. case "production":
  182. err = Initialize("app.production.yaml", cfg)
  183. default:
  184. panic("err confing")
  185. }
  186. if err != nil {
  187. panic(err)
  188. }
  189. cfg.JwtTokenKeyConfig = openPrivateKey()
  190. options = cfg
  191. })
  192. }