config.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package config
  2. import (
  3. "fmt"
  4. "log"
  5. "runtime"
  6. _ "github.com/go-sql-driver/mysql"
  7. "github.com/jmoiron/sqlx"
  8. "github.com/nats-io/nats.go"
  9. "github.com/spf13/viper"
  10. )
  11. type Config struct {
  12. Port int `json:"port,omitempty"`
  13. DataBase *DataBase `json:"database,omitempty"`
  14. MQ *MQ `json:"mq,omitempty"`
  15. }
  16. type DataBase struct {
  17. Name string `json:"name,omitempty"`
  18. Host string `json:"host,omitempty"`
  19. MaxOpenConns int `json:"maxOpenConns,omitempty"`
  20. MaxIdleConns int `json:"maxIdleConns,omitempty"`
  21. }
  22. type MQ struct {
  23. Name string `json:"name,omitempty"`
  24. Host string `json:"host,omitempty"`
  25. }
  26. var Conf *Config
  27. var DB *sqlx.DB
  28. var JS nats.JetStreamContext
  29. func InitConf() {
  30. if runtime.GOOS == "linux" {
  31. viper.SetConfigFile("./config-linux.yaml")
  32. } else {
  33. viper.SetConfigFile("./config.yaml")
  34. }
  35. if err := viper.ReadInConfig(); err != nil {
  36. panic("Read file error:" + err.Error())
  37. }
  38. var config Config
  39. if err := viper.Unmarshal(&config); err != nil {
  40. panic("File exchange error:" + err.Error())
  41. }
  42. Conf = &config
  43. }
  44. func InitDataBase() {
  45. var err error
  46. DB, err = sqlx.Connect(Conf.DataBase.Name, Conf.DataBase.Host)
  47. if err != nil {
  48. log.Fatalf("connect DB failed, err:%v\n", err)
  49. return
  50. }
  51. DB.SetMaxOpenConns(Conf.DataBase.MaxOpenConns)
  52. DB.SetMaxIdleConns(Conf.DataBase.MaxOpenConns)
  53. }
  54. func InitMQ() {
  55. conn, err := nats.Connect(Conf.MQ.Host)
  56. if err != nil {
  57. fmt.Println(err)
  58. }
  59. js, _ := conn.JetStream(nats.PublishAsyncMaxPending(256))
  60. js.AddStream(&nats.StreamConfig{
  61. Name: "EXAMS",
  62. Subjects: []string{"EXAMS.*"},
  63. })
  64. JS = js
  65. }
  66. func init() {
  67. // 1、初始化配置
  68. InitConf()
  69. // 2、初始化数据库
  70. InitDataBase()
  71. // 3、初始化MQ
  72. InitMQ()
  73. }