/db/db.go

https://github.com/LockGit/gochat · Go · 57 lines · 44 code · 7 blank · 6 comment · 6 complexity · 10c0481a2999ee5d40d920644b7a5fbc MD5 · raw file

  1. /**
  2. * Created by lock
  3. * Date: 2019-09-22
  4. * Time: 22:37
  5. */
  6. package db
  7. import (
  8. "github.com/jinzhu/gorm"
  9. _ "github.com/jinzhu/gorm/dialects/sqlite"
  10. "github.com/sirupsen/logrus"
  11. "gochat/config"
  12. "path/filepath"
  13. "sync"
  14. "time"
  15. )
  16. var dbMap = map[string]*gorm.DB{}
  17. var syncLock sync.Mutex
  18. func init() {
  19. initDB("gochat")
  20. }
  21. func initDB(dbName string) {
  22. var e error
  23. // if prod env , you should change mysql driver for yourself !!!
  24. realPath, _ := filepath.Abs("./")
  25. configFilePath := realPath + "/db/gochat.sqlite3"
  26. syncLock.Lock()
  27. dbMap[dbName], e = gorm.Open("sqlite3", configFilePath)
  28. dbMap[dbName].DB().SetMaxIdleConns(4)
  29. dbMap[dbName].DB().SetMaxOpenConns(20)
  30. dbMap[dbName].DB().SetConnMaxLifetime(8 * time.Second)
  31. if config.GetMode() == "dev" {
  32. dbMap[dbName].LogMode(true)
  33. }
  34. syncLock.Unlock()
  35. if e != nil {
  36. logrus.Error("connect db fail:%s", e.Error())
  37. }
  38. }
  39. func GetDb(dbName string) (db *gorm.DB) {
  40. if db, ok := dbMap[dbName]; ok {
  41. return db
  42. } else {
  43. return nil
  44. }
  45. }
  46. type DbGoChat struct {
  47. }
  48. func (*DbGoChat) GetDbName() string {
  49. return "gochat"
  50. }