| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- package cache
- import (
- "context"
- "encoding/json"
- "fmt"
- "github.com/redis/go-redis/v9"
- "server/global"
- "server/utils/common"
- "time"
- )
- var Redis redis.UniversalClient
- func init() {
- Redis = global.GVA_REDIS
- }
- const (
- //设备在线状态
- DeviceStateKey = "dev_camera_state_%s"
- )
- func CacheDeviceInfoKey(sn string) string {
- return fmt.Sprintf(DeviceStateKey, sn)
- }
- type CacheDeviceInfo struct {
- LastTime *common.Time //同步时间
- Status int //0不在线 1在线
- }
- // UpdateDeviceState 更新设备缓存的状态
- func UpdateDeviceState(sn string, status int) bool {
- lastTime := common.Time(time.Now())
- deviceInfo, _ := json.Marshal(CacheDeviceInfo{
- LastTime: &lastTime,
- Status: status,
- })
- if global.GVA_REDIS == nil {
- return false
- }
- err := global.GVA_REDIS.Set(context.Background(), CacheDeviceInfoKey(sn), deviceInfo, 0)
- if err.Err() != nil {
- global.GVA_LOG.Error(err.String())
- return false
- }
- return true
- }
- // GetCacheDeviceState 取缓存中的值
- func GetCacheDeviceState(sn string) (status int, lastTime *common.Time) {
- if global.GVA_REDIS == nil {
- return 0, nil
- }
- result, _ := global.GVA_REDIS.Get(context.Background(), CacheDeviceInfoKey(sn)).Result()
- if result == "" {
- return 0, nil
- }
- cacheInfo := CacheDeviceInfo{}
- err := json.Unmarshal([]byte(result), &cacheInfo)
- if err != nil {
- global.GVA_LOG.Error(err.Error())
- return 0, nil
- }
- return cacheInfo.Status, cacheInfo.LastTime
- }
|