dao.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package dao
  2. import (
  3. "context"
  4. "go-common/app/service/live/xrewardcenter/conf"
  5. "go-common/library/cache/memcache"
  6. "go-common/library/cache/redis"
  7. xsql "go-common/library/database/sql"
  8. "go-common/library/log"
  9. gift_api "go-common/app/service/live/gift/api/liverpc"
  10. room_api "go-common/app/service/live/room/api/liverpc"
  11. "go-common/library/net/rpc/liverpc"
  12. )
  13. // Dao dao
  14. type Dao struct {
  15. c *conf.Config
  16. mc *memcache.Pool
  17. redis *redis.Pool
  18. db *xsql.DB
  19. }
  20. // New init mysql db
  21. func New(c *conf.Config) (dao *Dao) {
  22. dao = &Dao{
  23. c: c,
  24. mc: memcache.NewPool(c.Memcache),
  25. redis: redis.NewPool(c.Redis),
  26. db: xsql.NewMySQL(c.MySQL),
  27. }
  28. return
  29. }
  30. // RoomAPI .
  31. var RoomAPI *room_api.Client
  32. // GiftAPI .
  33. var GiftAPI *gift_api.Client
  34. // InitAPI init all service APIs
  35. func InitAPI() {
  36. RoomAPI = room_api.New(getConf("room"))
  37. GiftAPI = gift_api.New(getConf("gift"))
  38. }
  39. func getConf(appName string) *liverpc.ClientConfig {
  40. c := conf.Conf.LiveRpc
  41. if c != nil {
  42. return c[appName]
  43. }
  44. return nil
  45. }
  46. // Close close the resource.
  47. func (d *Dao) Close() {
  48. d.mc.Close()
  49. d.redis.Close()
  50. d.db.Close()
  51. }
  52. // Ping dao ping
  53. func (d *Dao) Ping(c context.Context) error {
  54. if err := d.db.Ping(c); err != nil {
  55. log.Error("ping db error(%v)", err)
  56. return err
  57. }
  58. return d.pingMemcache(c)
  59. }
  60. func (d *Dao) pingMemcache(c context.Context) (err error) {
  61. conn := d.mc.Get(c)
  62. defer conn.Close()
  63. err = conn.Set(&memcache.Item{Key: "ping", Value: []byte("pong"), Expiration: 0})
  64. if err != nil {
  65. log.Error("mc.ping.Store error(%v)", err)
  66. return err
  67. }
  68. return err
  69. }