dao.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package dao
  2. import (
  3. "context"
  4. "time"
  5. "go-common/library/cache/memcache"
  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. // Dao dao.
  13. type Dao struct {
  14. db *sql.DB
  15. redis *redis.Pool
  16. redisExpire int32
  17. mc *memcache.Pool
  18. mcExpire int32
  19. }
  20. func checkErr(err error) {
  21. if err != nil {
  22. panic(err)
  23. }
  24. }
  25. // New new a dao and return.
  26. func New() (dao *Dao) {
  27. var (
  28. dc struct {
  29. Demo *sql.Config
  30. }
  31. rc struct {
  32. Demo *redis.Config
  33. DemoExpire xtime.Duration
  34. }
  35. mc struct {
  36. Demo *memcache.Config
  37. DemoExpire xtime.Duration
  38. }
  39. )
  40. checkErr(paladin.Get("mysql.toml").UnmarshalTOML(&dc))
  41. checkErr(paladin.Get("redis.toml").UnmarshalTOML(&rc))
  42. checkErr(paladin.Get("memcache.toml").UnmarshalTOML(&mc))
  43. dao = &Dao{
  44. // mysql
  45. db: sql.NewMySQL(dc.Demo),
  46. // redis
  47. redis: redis.NewPool(rc.Demo),
  48. redisExpire: int32(time.Duration(rc.DemoExpire) / time.Second),
  49. // memcache
  50. mc: memcache.NewPool(mc.Demo),
  51. mcExpire: int32(time.Duration(mc.DemoExpire) / time.Second),
  52. }
  53. return
  54. }
  55. // Close close the resource.
  56. func (d *Dao) Close() {
  57. d.mc.Close()
  58. d.redis.Close()
  59. d.db.Close()
  60. }
  61. // Ping ping the resource.
  62. func (d *Dao) Ping(ctx context.Context) (err error) {
  63. if err = d.pingMC(ctx); err != nil {
  64. return
  65. }
  66. if err = d.pingRedis(ctx); err != nil {
  67. return
  68. }
  69. return d.db.Ping(ctx)
  70. }
  71. func (d *Dao) pingMC(ctx context.Context) (err error) {
  72. conn := d.mc.Get(ctx)
  73. defer conn.Close()
  74. if err = conn.Set(&memcache.Item{Key: "ping", Value: []byte("pong"), Expiration: 0}); err != nil {
  75. log.Error("conn.Set(PING) error(%v)", err)
  76. }
  77. return
  78. }
  79. func (d *Dao) pingRedis(ctx context.Context) (err error) {
  80. conn := d.redis.Get(ctx)
  81. defer conn.Close()
  82. if _, err = conn.Do("SET", "ping", "pong"); err != nil {
  83. log.Error("conn.Set(PING) error(%v)", err)
  84. }
  85. return
  86. }