app.go 7.3 KB

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