dao.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. }