dao.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package dao
  2. import (
  3. "context"
  4. "fmt"
  5. "time"
  6. "go-common/library/cache/redis"
  7. "go-common/library/conf/paladin"
  8. "go-common/library/database/sql"
  9. "go-common/library/log"
  10. xtime "go-common/library/time"
  11. )
  12. const (
  13. _recInfoExpireTtl = 86400
  14. _recInfoKey = "rec_info_%d"
  15. )
  16. // Dao dao.
  17. type Dao struct {
  18. liveAppDb *sql.DB
  19. redis *redis.Pool
  20. redisExpire int32
  21. }
  22. func checkErr(err error) {
  23. if err != nil {
  24. panic(err)
  25. }
  26. }
  27. // New new a dao and return.
  28. func New() (dao *Dao) {
  29. var (
  30. dc struct {
  31. LiveApp *sql.Config
  32. }
  33. rc struct {
  34. Rec *redis.Config
  35. DemoExpire xtime.Duration
  36. }
  37. )
  38. checkErr(paladin.Get("mysql.toml").UnmarshalTOML(&dc))
  39. checkErr(paladin.Get("redis.toml").UnmarshalTOML(&rc))
  40. fmt.Printf("%+v", dc)
  41. dao = &Dao{
  42. // mysql
  43. liveAppDb: sql.NewMySQL(dc.LiveApp),
  44. // redis
  45. redis: redis.NewPool(rc.Rec),
  46. redisExpire: int32(time.Duration(rc.DemoExpire) / time.Second),
  47. }
  48. return
  49. }
  50. // Close close the resource.
  51. func (d *Dao) Close() {
  52. d.redis.Close()
  53. d.liveAppDb.Close()
  54. }
  55. // Ping ping the resource.
  56. func (d *Dao) Ping(ctx context.Context) (err error) {
  57. if err = d.pingRedis(ctx); err != nil {
  58. return
  59. }
  60. return d.liveAppDb.Ping(ctx)
  61. }
  62. func (d *Dao) pingRedis(ctx context.Context) (err error) {
  63. conn := d.redis.Get(ctx)
  64. defer conn.Close()
  65. if _, err = conn.Do("SET", "ping", "pong"); err != nil {
  66. log.Error("conn.Set(PING) error(%v)", err)
  67. }
  68. return
  69. }