redis.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package v2
  2. import (
  3. "context"
  4. "encoding/json"
  5. "time"
  6. "go-common/app/infra/config/model"
  7. "go-common/library/cache/redis"
  8. "go-common/library/log"
  9. )
  10. const (
  11. expireDuration = 3 * time.Hour
  12. )
  13. // Hosts return service hosts from redis.
  14. func (d *Dao) Hosts(c context.Context, svr string) (hosts []*model.Host, err error) {
  15. var (
  16. dels []string
  17. now = time.Now()
  18. conn = d.redis.Get(c)
  19. )
  20. defer conn.Close()
  21. res, err := redis.Strings(conn.Do("HGETALL", svr))
  22. if err != nil {
  23. log.Error("conn.Do(HGETALL, %s) error(%v)", svr, err)
  24. return
  25. }
  26. for i, r := range res {
  27. if i%2 == 0 {
  28. continue
  29. }
  30. h := &model.Host{}
  31. if err = json.Unmarshal([]byte(r), h); err != nil {
  32. log.Error("json.Unmarshal(%s) error(%v)", r, err)
  33. return
  34. }
  35. if now.Sub(h.HeartbeatTime.Time()) <= d.expire+5 {
  36. h.State = model.HostOnline
  37. hosts = append(hosts, h)
  38. } else if now.Sub(h.HeartbeatTime.Time()) >= expireDuration {
  39. dels = append(dels, h.Name)
  40. } else {
  41. h.State = model.HostOffline
  42. hosts = append(hosts, h)
  43. }
  44. }
  45. if len(dels) > 0 {
  46. if _, err1 := conn.Do("HDEL", svr, dels); err1 != nil {
  47. log.Error("conn.Do(HDEL, %s, %v) error(%v)", svr, dels, err1)
  48. }
  49. }
  50. return
  51. }
  52. // SetHost add service host to redis.
  53. func (d *Dao) SetHost(c context.Context, host *model.Host, svr string) (err error) {
  54. b, err := json.Marshal(host)
  55. if err != nil {
  56. log.Error("json.Marshal(%s) error(%v)", host, err)
  57. return
  58. }
  59. conn := d.redis.Get(c)
  60. defer conn.Close()
  61. if _, err = conn.Do("HSET", svr, host.Name, string(b)); err != nil {
  62. log.Error("conn.Do(SET, %s, %s, %v) error(%v)", svr, host.Name, host, err)
  63. }
  64. return
  65. }
  66. // ClearHost clear all hosts.
  67. func (d *Dao) ClearHost(c context.Context, svr string) (err error) {
  68. var (
  69. conn = d.redis.Get(c)
  70. )
  71. defer conn.Close()
  72. if _, err = conn.Do("DEL", svr); err != nil {
  73. log.Error("conn.Do(DEL, %s) error(%v)", svr, err)
  74. }
  75. return
  76. }
  77. // Ping check Redis connection
  78. func (d *Dao) pingRedis(c context.Context) (err error) {
  79. conn := d.redis.Get(c)
  80. _, err = conn.Do("SET", "PING", "PONG")
  81. conn.Close()
  82. return
  83. }