redis.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package utils
  2. import (
  3. "fmt"
  4. "github.com/go-redis/redis"
  5. "iot_manager_service/app/dao"
  6. "iot_manager_service/config"
  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. })
  22. _, err := Redis.Ping().Result()
  23. if err != nil {
  24. return err
  25. }
  26. return nil
  27. }
  28. const (
  29. UserKey = "user_%d"
  30. ModuleTypeKey = "module_type_%d"
  31. ControlTypeKey = "control_type_%d"
  32. ControlType = "control_type"
  33. ModuleType = "module_his_type"
  34. )
  35. func GetUserName(id int64) string {
  36. var name string
  37. key := fmt.Sprintf(UserKey, id)
  38. name, err := Redis.Get(key).Result()
  39. if err != nil {
  40. user := &dao.User{ID: id}
  41. if err := user.GetUser(); err != nil {
  42. fmt.Printf("GetUser err = %s \n", err)
  43. } else {
  44. name = user.Name
  45. Redis.Set(key, name, time.Second*10)
  46. }
  47. }
  48. return name
  49. }
  50. func GetModuleName(id int) string {
  51. var name string
  52. key := fmt.Sprintf(ModuleTypeKey, id)
  53. name, err := Redis.Get(key).Result()
  54. if err != nil {
  55. dict := &dao.Dict{Code: ModuleType, DictKey: strconv.Itoa(id)}
  56. if err := dict.GetByCodeAndKey(); err != nil {
  57. fmt.Printf("GetByCodeAndKey err = %d \n", err)
  58. } else {
  59. name = dict.DictValue
  60. Redis.Set(key, name, -1)
  61. }
  62. }
  63. return name
  64. }
  65. func GetControlType(id int) string {
  66. var name string
  67. key := fmt.Sprintf(ControlTypeKey, id)
  68. name, err := Redis.Get(key).Result()
  69. if err != nil {
  70. dict := &dao.Dict{Code: ControlType, DictKey: strconv.Itoa(id)}
  71. if err := dict.GetByCodeAndKey(); err != nil {
  72. fmt.Printf("GetByCodeAndKey err = %d \n", err)
  73. } else {
  74. name = dict.DictValue
  75. Redis.Set(key, name, -1)
  76. }
  77. }
  78. return name
  79. }