device_redis.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package cache
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/redis/go-redis/v9"
  7. "server/global"
  8. "server/utils/common"
  9. "time"
  10. )
  11. var Redis redis.UniversalClient
  12. func init() {
  13. Redis = global.GVA_REDIS
  14. }
  15. const (
  16. //设备在线状态
  17. DeviceStateKey = "dev_camera_state_%s"
  18. )
  19. func CacheDeviceInfoKey(sn string) string {
  20. return fmt.Sprintf(DeviceStateKey, sn)
  21. }
  22. type CacheDeviceInfo struct {
  23. LastTime *common.Time //同步时间
  24. Status int //0不在线 1在线
  25. }
  26. // UpdateDeviceState 更新设备缓存的状态
  27. func UpdateDeviceState(sn string, status int) bool {
  28. lastTime := common.Time(time.Now())
  29. deviceInfo, _ := json.Marshal(CacheDeviceInfo{
  30. LastTime: &lastTime,
  31. Status: status,
  32. })
  33. if global.GVA_REDIS == nil {
  34. return false
  35. }
  36. err := global.GVA_REDIS.Set(context.Background(), CacheDeviceInfoKey(sn), deviceInfo, 0)
  37. if err.Err() != nil {
  38. global.GVA_LOG.Error(err.String())
  39. return false
  40. }
  41. return true
  42. }
  43. // GetCacheDeviceState 取缓存中的值
  44. func GetCacheDeviceState(sn string) (status int, lastTime *common.Time) {
  45. if global.GVA_REDIS == nil {
  46. return 0, nil
  47. }
  48. result, _ := global.GVA_REDIS.Get(context.Background(), CacheDeviceInfoKey(sn)).Result()
  49. if result == "" {
  50. return 0, nil
  51. }
  52. cacheInfo := CacheDeviceInfo{}
  53. err := json.Unmarshal([]byte(result), &cacheInfo)
  54. if err != nil {
  55. global.GVA_LOG.Error(err.Error())
  56. return 0, nil
  57. }
  58. return cacheInfo.Status, cacheInfo.LastTime
  59. }