redis.go 892 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package util
  2. import (
  3. "fmt"
  4. "github.com/go-redis/redis"
  5. "iot_manager_service/config"
  6. "time"
  7. )
  8. var Redis *redis.Client
  9. func InitRedis() error {
  10. cfg := config.Instance()
  11. addr := cfg.Redis.Host
  12. Redis = redis.NewClient(&redis.Options{
  13. Addr: addr,
  14. DialTimeout: 10 * time.Second,
  15. ReadTimeout: 30 * time.Second,
  16. WriteTimeout: 30 * time.Second,
  17. PoolSize: 10,
  18. PoolTimeout: 30 * time.Second,
  19. Password: cfg.Redis.Password,
  20. })
  21. _, err := Redis.Ping().Result()
  22. if err != nil {
  23. return err
  24. }
  25. return nil
  26. }
  27. const (
  28. DeviceStateKey = "dev_state:%s"
  29. )
  30. //GetDeviceState 获取设备状态 1在线 2离线
  31. func GetDeviceState(sn string) int {
  32. key := fmt.Sprintf(DeviceStateKey, sn)
  33. value, err := Redis.Get(key).Int()
  34. state := 2
  35. if err != nil {
  36. fmt.Printf("GetDeviceState err = %s \n", err)
  37. return state
  38. }
  39. if value == 1 {
  40. state = 1
  41. }
  42. return state
  43. }