golang 的 rabbitmq 消费项目
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.

im_db.go 1.4 KiB

1 year ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package db
  2. import (
  3. "fmt"
  4. "os"
  5. "time"
  6. _ "github.com/go-sql-driver/mysql" //必须导入mysql驱动,否则会panic
  7. "xorm.io/xorm"
  8. "xorm.io/xorm/log"
  9. "applet/app/cfg"
  10. )
  11. var ImDb *xorm.Engine
  12. //根据DB配置文件初始化数据库
  13. func InitImDB(c *cfg.DBCfg) error {
  14. var (
  15. err error
  16. f *os.File
  17. )
  18. //创建Orm引擎
  19. if ImDb, err = xorm.NewEngine("mysql", fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4", c.User, c.Psw, c.Host, c.Name)); err != nil {
  20. return err
  21. }
  22. ImDb.SetConnMaxLifetime(c.MaxLifetime * time.Second) //设置最长连接时间
  23. ImDb.SetMaxOpenConns(c.MaxOpenConns) //设置最大打开连接数
  24. ImDb.SetMaxIdleConns(c.MaxIdleConns) //设置连接池的空闲数大小
  25. if err = ImDb.Ping(); err != nil { //尝试ping数据库
  26. return err
  27. }
  28. if c.ShowLog { //根据配置文件设置日志
  29. ImDb.ShowSQL(true) //设置是否打印sql
  30. ImDb.Logger().SetLevel(0) //设置日志等级
  31. //修改日志文件存放路径文件名是%s.log
  32. path := fmt.Sprintf(c.Path, c.Name)
  33. f, err = os.OpenFile(path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0777)
  34. if err != nil {
  35. os.RemoveAll(c.Path)
  36. if f, err = os.OpenFile(c.Path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0777); err != nil {
  37. return err
  38. }
  39. }
  40. logger := log.NewSimpleLogger(f)
  41. logger.ShowSQL(true)
  42. ImDb.SetLogger(logger)
  43. }
  44. return nil
  45. }