dao.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package black
  2. import (
  3. "context"
  4. "time"
  5. "go-common/app/interface/main/app-intl/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. // AddBlacklist is.
  40. func (d *Dao) AddBlacklist(mid, aid int64) {
  41. d.addCache(func() {
  42. d.addBlackCache(context.Background(), mid, aid)
  43. })
  44. }
  45. // DelBlacklist is.
  46. func (d *Dao) DelBlacklist(mid, aid int64) {
  47. d.addCache(func() {
  48. d.delBlackCache(context.Background(), mid, aid)
  49. })
  50. }
  51. // BlackList is.
  52. func (d *Dao) BlackList(c context.Context, mid int64) (aidm map[int64]struct{}, err error) {
  53. var ok bool
  54. if ok, err = d.expireBlackCache(c, mid); err != nil {
  55. return
  56. }
  57. if ok {
  58. aidm, err = d.blackCache(c, mid)
  59. }
  60. return
  61. }
  62. // addCache add cache to mc by goroutine
  63. func (d *Dao) addCache(i func()) {
  64. select {
  65. case d.aCh <- i:
  66. default:
  67. log.Warn("cacheproc chan full")
  68. }
  69. }
  70. // cacheproc cache proc
  71. func (d *Dao) cacheproc() {
  72. for {
  73. f, ok := <-d.aCh
  74. if !ok {
  75. log.Warn("cache proc exit")
  76. return
  77. }
  78. f()
  79. }
  80. }