dao.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package black
  2. import (
  3. "context"
  4. "time"
  5. "go-common/app/interface/main/app-feed/conf"
  6. "go-common/library/cache/redis"
  7. "go-common/library/log"
  8. httpx "go-common/library/net/http/blademaster"
  9. )
  10. // Dao is black dao.
  11. type Dao struct {
  12. // http clientAsyn
  13. clientAsyn *httpx.Client
  14. // redis
  15. redis *redis.Pool
  16. expireRds int32
  17. aCh chan func()
  18. }
  19. // New new a black dao.
  20. func New(c *conf.Config) (d *Dao) {
  21. d = &Dao{
  22. // http client
  23. clientAsyn: httpx.NewClient(c.HTTPClientAsyn),
  24. // redis init
  25. redis: redis.NewPool(c.Redis.Feed.Config),
  26. expireRds: int32(time.Duration(c.Redis.Feed.ExpireBlack) / time.Second),
  27. aCh: make(chan func(), 1024),
  28. }
  29. go d.cacheproc()
  30. return
  31. }
  32. // Ping Ping check redis connection
  33. func (d *Dao) Ping(c context.Context) (err error) {
  34. connRedis := d.redis.Get(c)
  35. _, err = connRedis.Do("SET", "PING", "PONG")
  36. connRedis.Close()
  37. return
  38. }
  39. func (d *Dao) AddBlacklist(mid, aid int64) {
  40. d.addCache(func() {
  41. d.addBlackCache(context.Background(), mid, aid)
  42. })
  43. }
  44. func (d *Dao) DelBlacklist(mid, aid int64) {
  45. d.addCache(func() {
  46. d.delBlackCache(context.Background(), mid, aid)
  47. })
  48. }
  49. func (d *Dao) BlackList(c context.Context, mid int64) (aidm map[int64]struct{}, err error) {
  50. var ok bool
  51. if ok, err = d.expireBlackCache(c, mid); err != nil {
  52. return
  53. }
  54. if ok {
  55. aidm, err = d.blackCache(c, mid)
  56. }
  57. return
  58. }
  59. // addCache add cache to mc by goroutine
  60. func (d *Dao) addCache(i func()) {
  61. select {
  62. case d.aCh <- i:
  63. default:
  64. log.Warn("cacheproc chan full")
  65. }
  66. }
  67. // cacheproc cache proc
  68. func (d *Dao) cacheproc() {
  69. for {
  70. f, ok := <-d.aCh
  71. if !ok {
  72. log.Warn("cache proc exit")
  73. return
  74. }
  75. f()
  76. }
  77. }