redis.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. )
  34. //GetDeviceState 获取设备状态 1在线 2离线
  35. func GetDeviceState(id string) (retTime time.Time, retState string) {
  36. defer func() {
  37. if err1 := recover(); err1 != nil {
  38. fmt.Println("GetDeviceState err = ", err1)
  39. }
  40. }()
  41. retTime = time.Time{}
  42. retState = "2"
  43. //redis中 0在线 1离线
  44. //todo 需要统一
  45. list, err := Redis.HMGet(DeviceStateKey+id, TLast, ONLINE).Result()
  46. if err == nil && list[0] != nil || list[1] != nil {
  47. t, err1 := common.MlParseTime(list[0].(string))
  48. s, err0 := strconv.Atoi(list[1].(string))
  49. if err0 == nil && err1 == nil {
  50. if s == 0 {
  51. retState = "1"
  52. }
  53. retTime = t
  54. }
  55. }
  56. return
  57. }