dao.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package videoshot
  2. import (
  3. "context"
  4. "go-common/library/cache/redis"
  5. "go-common/library/database/sql"
  6. "go-common/library/log"
  7. "go-common/library/stat/prom"
  8. "go-common/app/service/main/archive/conf"
  9. "go-common/app/service/main/archive/model/videoshot"
  10. )
  11. // Dao is videoshot dao.
  12. type Dao struct {
  13. // mysql
  14. db *sql.DB
  15. dbRead *sql.DB
  16. getStmt *sql.Stmt
  17. inStmt *sql.Stmt
  18. // redis
  19. rds *redis.Pool
  20. // prom
  21. infoProm *prom.Prom
  22. // chan
  23. cacheCh chan func()
  24. }
  25. // New new a videoshot dao.
  26. func New(c *conf.Config) (d *Dao) {
  27. d = &Dao{
  28. db: sql.NewMySQL(c.DB.Arc),
  29. dbRead: sql.NewMySQL(c.DB.ArcRead),
  30. rds: redis.NewPool(c.Redis.Archive.Config),
  31. cacheCh: make(chan func(), 1024),
  32. }
  33. d.getStmt = d.dbRead.Prepared(_getSQL)
  34. d.inStmt = d.db.Prepared(_inSQL)
  35. d.infoProm = prom.BusinessInfoCount
  36. go d.cacheproc()
  37. return d
  38. }
  39. // Videoshot get videoshot.
  40. func (d *Dao) Videoshot(c context.Context, cid int64) (v *videoshot.Videoshot, err error) {
  41. var count, ver int
  42. if count, ver, err = d.cache(c, cid); err != nil {
  43. log.Error("d.cache(%d) error(%v)", cid, err)
  44. err = nil // NOTE: ignore error use db
  45. }
  46. if count != 0 {
  47. v = &videoshot.Videoshot{Cid: cid, Count: count}
  48. v.SetVersion(ver)
  49. return
  50. }
  51. if v, err = d.videoshot(c, cid); err != nil || v == nil {
  52. log.Warn("d.videoshot(%d) error(%v) or v==nil", cid, err)
  53. return
  54. }
  55. d.cacheCh <- func() {
  56. d.addCache(context.TODO(), v.Cid, v.Version(), v.Count)
  57. }
  58. return
  59. }
  60. // AddVideoshot add videoshot.
  61. func (d *Dao) AddVideoshot(c context.Context, v *videoshot.Videoshot) (err error) {
  62. if _, err = d.addVideoshot(c, v); err != nil {
  63. log.Error("d.addVideoshot(%v) error(%v)", v, err)
  64. return
  65. }
  66. d.cacheCh <- func() {
  67. d.addCache(context.TODO(), v.Cid, v.Version(), v.Count)
  68. }
  69. return
  70. }
  71. // Close close resource.
  72. func (d *Dao) Close() {
  73. if d.rds != nil {
  74. d.rds.Close()
  75. }
  76. if d.db != nil {
  77. d.db.Close()
  78. }
  79. close(d.cacheCh)
  80. }
  81. // Ping ping success.
  82. func (d *Dao) Ping(c context.Context) (err error) {
  83. conn := d.rds.Get(c)
  84. _, err = conn.Do("SET", "PING", "PONG")
  85. conn.Close()
  86. return
  87. }
  88. func (d *Dao) cacheproc() {
  89. for {
  90. f, ok := <-d.cacheCh
  91. if !ok {
  92. return
  93. }
  94. f()
  95. }
  96. }