online.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. gredis.SetConfig(gredis.Config{
  20. Host: host,
  21. Port: port,
  22. Db: db,
  23. MaxActive: 100,
  24. })
  25. mgr := &Manager{
  26. redisClient: gredis.Instance(),
  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) SetHeartbeat(id string) error {
  58. status, err := mgr.GetStatus(id)
  59. if err != nil {
  60. return err
  61. }
  62. if status == nil {
  63. return errors.New("device offline")
  64. }
  65. key := KeyPrefix + id
  66. _, err = mgr.redisClient.Do("EXPIRE", key, status.HeartbeatInterval+status.HeartbeatInterval/2)
  67. if err != nil {
  68. return err
  69. }
  70. return nil
  71. }
  72. func (mgr *Manager) GetOffline(id string) error {
  73. key := KeyPrefix + id
  74. _, err := mgr.redisClient.Do("DEL", key)
  75. if err != nil {
  76. return err
  77. }
  78. return nil
  79. }