device_real_time_data.go 1.3 KB
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
}