redis.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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中 0在线 1离线
  46. //todo 需要统一
  47. list, err := Redis.HMGet(DeviceStateKey+id, TLast, ONLINE).Result()
  48. if err == nil && list[0] != nil || list[1] != nil {
  49. t, err1 := common.MlParseTime(list[0].(string))
  50. s, err0 := strconv.Atoi(list[1].(string))
  51. if err0 == nil && err1 == nil {
  52. if s == 0 {
  53. retState = "1"
  54. }
  55. retTime = t
  56. }
  57. }
  58. return
  59. }
  60. //GetDeviceData 获取设备数据 时间 key-value
  61. func GetDeviceData(id string) (retTime time.Time, values map[int]float32) {
  62. values = make(map[int]float32)
  63. if mapData, err := Redis.HGetAll(DeviceDataKey + id).Result(); err == nil {
  64. for k, v1 := range mapData {
  65. if k == TIME {
  66. if t, err := common.MlParseTime(v1); err == nil {
  67. retTime = t
  68. }
  69. } else {
  70. if sid, err := strconv.Atoi(k); err == nil {
  71. if val, err := strconv.ParseFloat(v1, 32); err == nil {
  72. values[sid] = float32(val)
  73. }
  74. }
  75. }
  76. }
  77. }
  78. return
  79. }