app.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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. Indicators string `yaml:"indicators"` // 牛只指标
  46. GenerateWorkOrder string `yaml:"generate_work_order"` // 生成工作单
  47. ImmunizationPlan string `yaml:"immunization_plan"` // 免疫计划
  48. SameTimePlan string `yaml:"same_time_plan"` // 同期
  49. UpdateSameTime string `yaml:"update_same_time"` // 更新同期
  50. SystemBasicCrontab string `yaml:"system_basic_crontab"` // 系统基础定时任务
  51. DeleteOldOriginal string `yaml:"delete_old_original"` // 删除脖环历史数据
  52. UpdateDiseaseToCalendar string `yaml:"update_disease_to_calendar"` // 更新每天治疗中牛头数到日历表中
  53. CowPregnant string `yaml:"cow_pregnant"` // 月度牛只怀孕清单
  54. UpdateActiveHabit string `yaml:"update_active_habit"` // 脖环2小时数据重新整合
  55. NeckRingEstrus string `yaml:"neck_ring_estrus"` // 脖环牛只发情
  56. NeckRingMerge string `yaml:"neck_ring_merge"` // 脖环原始数据合并
  57. NeckRingCalculate string `yaml:"neck_ring_calculate"` // 脖环数据计算
  58. NeckRingEstrusWarning string `yaml:"neck_ring_estrus_warning"` // 脖环发情预警
  59. NeckRingHealthWarning string `yaml:"neck_ring_health_warning"` // 脖环健康预警
  60. UpdatePenBehavior string `yaml:"update_pen_behavior"` // 栏舍行为数据
  61. UpdatePenBehaviorDaily string `yaml:"update_pen_behavior_daily"` // 栏舍饲养监测
  62. }
  63. type JwtTokenKeyConfig struct {
  64. PrivateKey *rsa.PrivateKey `json:"privateKey"`
  65. PublicKey *rsa.PublicKey `json:"publicKey"`
  66. }
  67. type WechatSetting struct {
  68. Appid string `yaml:"appid"`
  69. Secret string `yaml:"secret"`
  70. }
  71. type ExcelSetting struct {
  72. SheetName string `yaml:"sheet_name"` // = "Sheet1" //默认Sheet名称
  73. Height float64 `yaml:"height"` // = 25.0 //默认行高度
  74. }
  75. // StoreSetting 数据库配置
  76. type StoreSetting struct {
  77. // 开启 SyDb SQL 记录
  78. DriverName string `yaml:"driver_name" json:"driver_name"`
  79. ShowSQL bool `yaml:"show_sql" json:"show_sql"`
  80. KptRW string `yaml:"kpt_rw" json:"kpt_rw"`
  81. KptMigr string `yaml:"kpt_migr" json:"kpt_migr"`
  82. KptMqtt string `yaml:"kpt_mqtt" json:"kpt_mqtt"`
  83. }
  84. type RedisSetting struct {
  85. // sso 配置
  86. CacheRedis CacheRedisDB `json:"cache_redis" yaml:"cache_redis"`
  87. }
  88. type CacheRedisDB struct {
  89. Addr string `json:"addr" yaml:"addr"`
  90. DB int `json:"db" yaml:"db"`
  91. Requirepass string `json:"requirepass" yaml:"requirepass"`
  92. Expiry int `json:"expiry" yaml:"expiry"`
  93. }
  94. type SideWorkSetting struct {
  95. // Asynq 配置
  96. AsynqSetting AsynqSetting `json:"asynq_setting,omitempty" yaml:"asynq_setting"`
  97. }
  98. type AsynqSetting struct {
  99. Redis AsynqRedisSetting `json:"redis" yaml:"redis"`
  100. Queues map[string]int `json:"queues,omitempty" yaml:"queues"`
  101. Concurrency int `json:"concurrency,omitempty" yaml:"concurrency"`
  102. LogLevel int32 `json:"log_level,omitempty" yaml:"log_level"`
  103. }
  104. type AsynqRedisSetting struct {
  105. // Network type to use, either tcp or unix.
  106. // Default is tcp.
  107. Network string `json:"network,omitempty" yaml:"network"`
  108. // Redis server address in "host:port" format.
  109. Addr string `json:"addr,omitempty" yaml:"addr"`
  110. // Username to authenticate the current connection when Redis ACLs are used.
  111. // See: https://redis.io/commands/auth.
  112. Username string `json:"username,omitempty" yaml:"username"`
  113. // Password to authenticate the current connection.
  114. // See: https://redis.io/commands/auth.
  115. Password string `json:"password,omitempty" yaml:"password"`
  116. // Redis DB to select after connecting to a server.
  117. // See: https://redis.io/commands/select.
  118. DB int `json:"db,omitempty" yaml:"db"`
  119. // Dial timeout for establishing new connections.
  120. // Default is 5 seconds.
  121. DialTimeout time.Duration `json:"dialTimeout,omitempty" yaml:"dial_timeout"`
  122. // Timeout for socket reads.
  123. // If timeout is reached, read 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 3 seconds.
  128. ReadTimeout time.Duration `json:"readTimeout,omitempty" yaml:"read_timeout"`
  129. // Timeout for socket writes.
  130. // If timeout is reached, write commands will fail with a timeout error
  131. // instead of blocking.
  132. //
  133. // Use value -1 for no timeout and 0 for default.
  134. // Default is ReadTimout.
  135. WriteTimeout time.Duration `json:"writeTimeout,omitempty" yaml:"write_timeout"`
  136. // Maximum number of socket connections.
  137. // Default is 10 connections per every CPU as reported by runtime.NumCPU.
  138. PoolSize int `json:"poolSize,omitempty" yaml:"pool_size"`
  139. // TLS Config used to connect to a server.
  140. // TLS will be negotiated only if this field is set.
  141. TLSConfig *tls.Config `json:"tlsConfig,omitempty" yaml:"tls_config"`
  142. }
  143. type MqttSetting struct {
  144. Broker string `json:"broker" yaml:"broker"`
  145. UserName string `json:"username" yaml:"username"`
  146. Password string `json:"password" yaml:"password"`
  147. SubTopic string `json:"sub_topic" yaml:"sub_topic"`
  148. Retain bool `json:"retain" yaml:"retain"`
  149. Qos int `json:"qos" yaml:"qos"`
  150. KeepAlive int `json:"keepAlive" yaml:"keep_alive"`
  151. ConnectTimeout int `json:"connectTimeout" yaml:"connect_timeout"`
  152. AutoReconnect bool `json:"autoReconnect" yaml:"auto_reconnect"`
  153. ReconnectInterval int `json:"reconnectInterval" yaml:"reconnect_interval"`
  154. WorkNumber int `json:"workNumber" yaml:"work_number"`
  155. MergeDataTicker int `json:"mergeDataTicker" yaml:"merge_data_ticker"`
  156. }
  157. func (a *AppConfig) Name() string {
  158. return fmt.Sprintf("%s-%s", a.AppName, a.AppEnv)
  159. }
  160. // CacheNameSpace 作为 Key 的前缀,用来区分不同环境,不同 APP 下的 Key,防止缓存干扰
  161. // 踩坑记录:
  162. //
  163. // 如果使用 fmt.Sprintf("%s-%s-%s", a.AppName, a.AppRole, a.AppEnv),例如 sayam-http-production, sayam-consumer-production
  164. // 会导致 从 role http 写入的 key,从 role consumer 中取不出来,反之亦然
  165. // 支持更多的key空间, 可以更灵活的定义ns
  166. func (a *AppConfig) CacheNameSpace() string {
  167. cacheKeySpace := ""
  168. if a.FarmName != "" {
  169. cacheKeySpace = fmt.Sprintf("%s-%s-%s", a.AppName, a.AppEnv, a.FarmName)
  170. } else {
  171. cacheKeySpace = fmt.Sprintf("%s-%s", a.AppName, a.AppEnv)
  172. }
  173. return cacheKeySpace
  174. }
  175. func Options() *AppConfig {
  176. return options
  177. }
  178. func init() {
  179. appEnv = strings.ToLower(os.Getenv("APP_ENVIRONMENT"))
  180. cfg := &AppConfig{}
  181. var err error
  182. initOnce.Do(func() {
  183. switch appEnv {
  184. case "test":
  185. err = Initialize("app.test.yaml", cfg)
  186. case "development":
  187. err = Initialize("app.develop.yaml", cfg)
  188. case "production":
  189. err = Initialize("app.production.yaml", cfg)
  190. default:
  191. panic("err confing")
  192. }
  193. if err != nil {
  194. panic(err)
  195. }
  196. cfg.JwtTokenKeyConfig = openPrivateKey()
  197. options = cfg
  198. })
  199. }