You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

65 lines
1.2 KiB

  1. package db
  2. import (
  3. "egg-im/config"
  4. "egg-im/pkg/logger"
  5. "egg-im/pkg/util"
  6. "fmt"
  7. "github.com/go-redis/redis"
  8. "github.com/jinzhu/gorm"
  9. _ "github.com/go-sql-driver/mysql"
  10. )
  11. var (
  12. DB *gorm.DB
  13. RedisCli *redis.Client
  14. RedisUtil *util.RedisUtil
  15. )
  16. func Init() {
  17. InitMysql(config.MySQL)
  18. InitRedis(config.RedisIP, config.RedisPassword)
  19. }
  20. // InitMysql 初始化MySQL
  21. func InitMysql(dataSource string) {
  22. logger.Logger.Info("init mysql")
  23. var err error
  24. DB, err = gorm.Open("mysql", dataSource)
  25. if err != nil {
  26. panic(err)
  27. }
  28. DB.SingularTable(true)
  29. DB.LogMode(true)
  30. logger.Logger.Info("init mysql ok")
  31. }
  32. // InitRedis 初始化Redis
  33. func InitRedis(addr, password string) {
  34. logger.Logger.Info("init redis")
  35. RedisCli = redis.NewClient(&redis.Options{
  36. Addr: addr,
  37. DB: 1, //TODO::IM统一放1号库
  38. Password: password,
  39. })
  40. _, err := RedisCli.Ping().Result()
  41. if err != nil {
  42. panic(err)
  43. }
  44. RedisUtil = util.NewRedisUtil(RedisCli)
  45. logger.Logger.Info("init redis ok")
  46. }
  47. // InitByTest 初始化数据库配置,仅用在单元测试
  48. func InitByTest() {
  49. fmt.Println("init db")
  50. logger.Target = logger.Console
  51. InitMysql(config.MySQL)
  52. InitRedis(config.RedisIP, config.RedisPassword)
  53. }