redis.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package cache
  2. import (
  3. "fmt"
  4. "github.com/go-redis/redis"
  5. "iot_manager_service/config"
  6. "iot_manager_service/util/common"
  7. "strconv"
  8. "time"
  9. )
  10. var Redis *redis.Client
  11. func InitRedis() error {
  12. cfg := config.Instance()
  13. addr := cfg.Redis.Host
  14. Redis = redis.NewClient(&redis.Options{
  15. Addr: addr,
  16. DialTimeout: 10 * time.Second,
  17. ReadTimeout: 30 * time.Second,
  18. WriteTimeout: 30 * time.Second,
  19. PoolSize: 10,
  20. PoolTimeout: 30 * time.Second,
  21. Password: cfg.Redis.Password,
  22. })
  23. _, err := Redis.Ping().Result()
  24. if err != nil {
  25. return err
  26. }
  27. return nil
  28. }
  29. const (
  30. DeviceStateKey = "dev_stat_"
  31. ONLINE = "online"
  32. TLast = "tlast"
  33. DeviceDataKey = "dev_data_"
  34. TIME = "time"
  35. )
  36. //GetDeviceState 获取设备状态 1在线 2离线
  37. func GetDeviceState(id string) (retTime time.Time, retState string) {
  38. defer func() {
  39. if err1 := recover(); err1 != nil {
  40. fmt.Println("GetDeviceState err = ", err1)
  41. }
  42. }()
  43. retTime = time.Time{}
  44. retState = "2"
  45. //redis中 1在线 0离线
  46. //todo 需要统一
  47. list, err := Redis.HMGet(DeviceStateKey+id, TLast, ONLINE).Result()
  48. //fmt.Printf("list = %v id=%v \n", list, id)
  49. if err == nil && list[0] != nil || list[1] != nil {
  50. t, err1 := common.MlParseTime(list[0].(string))
  51. s, err0 := strconv.Atoi(list[1].(string))
  52. if err0 == nil && err1 == nil {
  53. if s == 1 {
  54. retState = "1"
  55. }
  56. retTime = t
  57. }
  58. }
  59. return
  60. }
  61. //GetDeviceData 获取设备数据 时间 key-value
  62. func GetDeviceData(id string) (retTime time.Time, values map[int]float32) {
  63. values = make(map[int]float32)
  64. if mapData, err := Redis.HGetAll(DeviceDataKey + id).Result(); err == nil {
  65. for k, v1 := range mapData {
  66. if k == TIME {
  67. if t, err := common.MlParseTime(v1); err == nil {
  68. retTime = t
  69. }
  70. } else {
  71. if sid, err := strconv.Atoi(k); err == nil {
  72. if val, err := strconv.ParseFloat(v1, 32); err == nil {
  73. values[sid] = float32(val)
  74. }
  75. }
  76. }
  77. }
  78. }
  79. return
  80. }