dao.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package dao
  2. import (
  3. "context"
  4. "go-common/app/service/bbq/topic/api"
  5. "go-common/library/sync/pipeline/fanout"
  6. "time"
  7. "go-common/library/cache/redis"
  8. "go-common/library/conf/paladin"
  9. "go-common/library/database/sql"
  10. "go-common/library/log"
  11. xtime "go-common/library/time"
  12. )
  13. //go:generate $GOPATH/src/go-common/app/tool/cache/gen
  14. type _cache interface {
  15. // cache: -sync=true -batch=10 -max_group=10 -batch_err=break -nullcache=&api.VideoExtension{Svid:-1} -check_null_code=$==nil||$.Svid==-1
  16. VideoExtension(c context.Context, ids []int64) (map[int64]*api.VideoExtension, error)
  17. // cache: -sync=true -batch=10 -max_group=10 -batch_err=break -nullcache=&api.TopicInfo{TopicId:-1} -check_null_code=$==nil||$.TopicId==-1
  18. TopicInfo(c context.Context, ids []int64) (map[int64]*api.TopicInfo, error)
  19. }
  20. // Dao dao.
  21. type Dao struct {
  22. cache *fanout.Fanout
  23. db *sql.DB
  24. redis *redis.Pool
  25. topicExpire int32
  26. }
  27. func checkErr(err error) {
  28. if err != nil {
  29. panic(err)
  30. }
  31. }
  32. // New new a dao and return.
  33. func New() (dao *Dao) {
  34. var (
  35. dc struct {
  36. Topic *sql.Config
  37. }
  38. rc struct {
  39. Topic *redis.Config
  40. TopicExpire xtime.Duration
  41. }
  42. )
  43. checkErr(paladin.Get("mysql.toml").UnmarshalTOML(&dc))
  44. checkErr(paladin.Get("redis.toml").UnmarshalTOML(&rc))
  45. dao = &Dao{
  46. cache: fanout.New("cache", fanout.Worker(1), fanout.Buffer(1024)),
  47. // mysql
  48. db: sql.NewMySQL(dc.Topic),
  49. // redis
  50. redis: redis.NewPool(rc.Topic),
  51. topicExpire: int32(time.Duration(rc.TopicExpire) / time.Second),
  52. }
  53. return
  54. }
  55. // Close close the resource.
  56. func (d *Dao) Close() {
  57. d.redis.Close()
  58. d.db.Close()
  59. }
  60. // Ping ping the resource.
  61. func (d *Dao) Ping(ctx context.Context) (err error) {
  62. if err = d.pingRedis(ctx); err != nil {
  63. return
  64. }
  65. return d.db.Ping(ctx)
  66. }
  67. func (d *Dao) pingRedis(ctx context.Context) (err error) {
  68. conn := d.redis.Get(ctx)
  69. defer conn.Close()
  70. if _, err = conn.Do("SET", "ping", "pong"); err != nil {
  71. log.Error("conn.Set(PING) error(%v)", err)
  72. }
  73. return
  74. }