redis.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package cache
  2. import (
  3. "encoding/json"
  4. "github.com/go-redis/redis"
  5. "iot_manager_service/app/user/dao"
  6. "iot_manager_service/config"
  7. "time"
  8. )
  9. var Redis *redis.Client
  10. func InitRedis() error {
  11. cfg := config.Instance()
  12. addr := cfg.Redis.Host
  13. Redis = redis.NewClient(&redis.Options{
  14. Addr: addr,
  15. DialTimeout: 10 * time.Second,
  16. ReadTimeout: 30 * time.Second,
  17. WriteTimeout: 30 * time.Second,
  18. PoolSize: 10,
  19. PoolTimeout: 30 * time.Second,
  20. Password: cfg.Redis.Password,
  21. DB: 1, //指定 哪个数据库,不然找不到数据
  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. // 将当前用户存入到redis中
  37. func SetNowSysUser(uid string, user *dao.SysUser) {
  38. marshal, _ := json.Marshal(user)
  39. Redis.Set("login:"+uid, marshal, time.Hour*24*7)
  40. }
  41. // 从redis中取出当前用户
  42. func GetNowSysUser(uid string) (*dao.SysUser, error) {
  43. result, _ := Redis.Get("login:" + uid).Result()
  44. str := []byte(result)
  45. nowuser := dao.SysUser{}
  46. err := json.Unmarshal(str, &nowuser)
  47. return &nowuser, err
  48. }
  49. // 将当前用户从redis中删除(退出登录)
  50. func DeleteToken(uid string) error {
  51. return Redis.Del("login:" + uid).Err()
  52. }
  53. // 存储离线用户的消息
  54. func StoreMessages(id, msg string) error {
  55. return Redis.LPush("offline:"+id, msg).Err()
  56. }
  57. // 获取用户的离线信息
  58. func GetStoreMessages(id string) []string {
  59. result, _ := Redis.LRange("offline:"+id, 0, -1).Result()
  60. return result
  61. }