device_real_time_data.go
1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package redis
import (
"fmt"
"github.com/go-redis/redis"
"github.com/linmadan/egglib-go/utils/json"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
)
/*
保存实时数据
device 设备号
record 记录
saveNotExists true:不存在才保存 false:直接覆盖
*/
func SaveDeviceRealTimeData(device string, record interface{}, saveNotExists bool) error {
client := GetRedis()
recordData, err := json.Marshal(record)
if err != nil {
return err
}
key := DeviceRealTimeDataKey(device)
// 已存在的不做保存
if saveNotExists {
if exists, err := client.Exists(key).Result(); exists > 0 && err == nil {
return nil
}
}
result := client.Set(key, recordData, 0)
_, err = result.Result()
return err
}
/*
获取实时数据
*/
func GetDeviceRealTimeData(device string, val interface{}) error {
client := GetRedis()
key := DeviceRealTimeDataKey(device)
result := client.Get(key)
data, err := result.Bytes()
if err == redis.Nil {
return domain.ErrorNotFound
}
if err = json.Unmarshal(data, val); err != nil {
return err
}
return nil
}
func DeviceRealTimeDataKey(deviceType string) string {
str := fmt.Sprintf("%v:device-realtime-data:%v", constant.CACHE_PREFIX, deviceType)
return str
}