dao.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package dao
  2. import (
  3. "context"
  4. relation "go-common/app/service/main/relation/api"
  5. "time"
  6. recallv1 "go-common/app/service/bbq/recsys-recall/api/grpc/v1"
  7. "go-common/app/service/bbq/recsys/conf"
  8. searchv1 "go-common/app/service/bbq/search/api/grpc/v1"
  9. user "go-common/app/service/bbq/user/api"
  10. "go-common/library/cache/memcache"
  11. "go-common/library/cache/redis"
  12. xsql "go-common/library/database/sql"
  13. "go-common/library/net/rpc/warden"
  14. "github.com/Dai0522/workpool"
  15. )
  16. // Dao dao
  17. type Dao struct {
  18. c *conf.Config
  19. mc *memcache.Pool
  20. redis *redis.Pool
  21. bfRedis *redis.Pool
  22. db *xsql.DB
  23. wp *workpool.Pool
  24. SearchClient searchv1.SearchClient
  25. RecallClient recallv1.RecsysRecallClient
  26. UserClient user.UserClient
  27. RelationClient relation.RelationClient
  28. }
  29. // New init mysql db
  30. func New(c *conf.Config) (dao *Dao) {
  31. wpConf := &workpool.PoolConfig{
  32. MaxWorkers: c.WorkerPool.MaxWorkers,
  33. MaxIdleWorkers: c.WorkerPool.MaxIdleWorkers,
  34. MinIdleWorkers: c.WorkerPool.MinIdleWorkers,
  35. KeepAlive: time.Duration(c.WorkerPool.KeepAlive),
  36. }
  37. wp, err := workpool.NewWorkerPool(1024, wpConf)
  38. if err != nil {
  39. panic(err)
  40. }
  41. wp.Start()
  42. dao = &Dao{
  43. c: c,
  44. redis: redis.NewPool(c.Redis),
  45. bfRedis: redis.NewPool(c.BFRedis),
  46. db: xsql.NewMySQL(c.MySQL),
  47. wp: wp,
  48. RecallClient: newRecallClient(c.GRPCClient["recall"]),
  49. UserClient: newUserClient(c.GRPCClient["user"]),
  50. RelationClient: newRelationClient(c.GRPCClient["relation"]),
  51. }
  52. return
  53. }
  54. func newRecallClient(cfg *conf.GRPCConfig) recallv1.RecsysRecallClient {
  55. cc, err := warden.NewClient(cfg.WardenConf).Dial(context.Background(), cfg.Addr)
  56. if err != nil {
  57. panic(err)
  58. }
  59. return recallv1.NewRecsysRecallClient(cc)
  60. }
  61. func newUserClient(cfg *conf.GRPCConfig) user.UserClient {
  62. cc, err := warden.NewClient(cfg.WardenConf).Dial(context.Background(), cfg.Addr)
  63. if err != nil {
  64. panic(err)
  65. }
  66. return user.NewUserClient(cc)
  67. }
  68. func newRelationClient(cfg *conf.GRPCConfig) relation.RelationClient {
  69. cc, err := warden.NewClient(cfg.WardenConf).Dial(context.Background(), cfg.Addr)
  70. if err != nil {
  71. panic(err)
  72. }
  73. return relation.NewRelationClient(cc)
  74. }
  75. // Close close the resource.
  76. func (d *Dao) Close() {
  77. d.mc.Close()
  78. d.redis.Close()
  79. d.bfRedis.Close()
  80. d.db.Close()
  81. }
  82. // Ping dao ping
  83. func (d *Dao) Ping(c context.Context) error {
  84. // TODO: if you need use mc,redis, please add
  85. return d.db.Ping(c)
  86. }