online.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. package online
  2. import (
  3. "errors"
  4. "github.com/gogf/gf/database/gredis"
  5. "github.com/gogf/gf/util/gconv"
  6. )
  7. const (
  8. KeyPrefix = "device:onlinestatus:"
  9. )
  10. type Status struct {
  11. ClientIP string
  12. AccessRPCHost string
  13. HeartbeatInterval uint32
  14. }
  15. type Manager struct {
  16. redisClient *gredis.Redis
  17. }
  18. func NewManager(host string, port, db int) *Manager {
  19. red := gredis.New(&gredis.Config{
  20. Host: host,
  21. Port: port,
  22. Db: db,
  23. MaxActive: 100,
  24. })
  25. mgr := &Manager{
  26. redisClient: red,
  27. }
  28. return mgr
  29. }
  30. func (mgr *Manager) GetStatus(id string) (*Status, error) {
  31. key := KeyPrefix + id
  32. status := new(Status)
  33. // get status from redis
  34. result, err := mgr.redisClient.DoVar("GET", key)
  35. if err != nil {
  36. return nil, err
  37. }
  38. err = result.Struct(status)
  39. if err != nil {
  40. return nil, err
  41. }
  42. return status, nil
  43. }
  44. func (mgr *Manager) GetOnline(id string, status Status) error {
  45. key := KeyPrefix + id
  46. buffStr := gconv.String(&status)
  47. _, err := mgr.redisClient.Do("SET", key, buffStr)
  48. if err != nil {
  49. return err
  50. }
  51. _, err = mgr.redisClient.Do("EXPIRE", key, status.HeartbeatInterval+status.HeartbeatInterval/2)
  52. if err != nil {
  53. return err
  54. }
  55. return nil
  56. }
  57. func (mgr *Manager) GetOnlineV2(id string, status Status) error {
  58. key := KeyPrefix + id
  59. buffStr := gconv.String(&status)
  60. _, err := mgr.redisClient.Do("SET", key, buffStr)
  61. if err != nil {
  62. return err
  63. }
  64. return nil
  65. }
  66. func (mgr *Manager) SetHeartbeat(id string) error {
  67. status, err := mgr.GetStatus(id)
  68. if err != nil {
  69. return err
  70. }
  71. if status == nil {
  72. return errors.New("device offline")
  73. }
  74. key := KeyPrefix + id
  75. _, err = mgr.redisClient.Do("EXPIRE", key, status.HeartbeatInterval+status.HeartbeatInterval/2)
  76. if err != nil {
  77. return err
  78. }
  79. return nil
  80. }
  81. func (mgr *Manager) GetOffline(id string) error {
  82. key := KeyPrefix + id
  83. _, err := mgr.redisClient.Do("DEL", key)
  84. if err != nil {
  85. return err
  86. }
  87. return nil
  88. }