redis.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package util
  2. import (
  3. "fmt"
  4. "github.com/go-redis/redis"
  5. "iot_manager_service/app/device/dao"
  6. dao2 "iot_manager_service/app/system/dao"
  7. "iot_manager_service/config"
  8. "strconv"
  9. "time"
  10. )
  11. var Redis *redis.Client
  12. func InitRedis() error {
  13. cfg := config.Instance()
  14. addr := cfg.Redis.Host
  15. Redis = redis.NewClient(&redis.Options{
  16. Addr: addr,
  17. DialTimeout: 10 * time.Second,
  18. ReadTimeout: 30 * time.Second,
  19. WriteTimeout: 30 * time.Second,
  20. PoolSize: 10,
  21. PoolTimeout: 30 * time.Second,
  22. })
  23. _, err := Redis.Ping().Result()
  24. if err != nil {
  25. return err
  26. }
  27. return nil
  28. }
  29. const (
  30. UserKey = "user_%d"
  31. ModuleTypeKey = "module_type_%d"
  32. ControlTypeKey = "control_type_%d"
  33. ControlType = "control_type"
  34. ModuleType = "module_his_type"
  35. )
  36. func GetUserName(id int64) string {
  37. var name string
  38. key := fmt.Sprintf(UserKey, id)
  39. name, err := Redis.Get(key).Result()
  40. if err != nil {
  41. user := &dao2.User{ID: id}
  42. if err := user.GetUser(); err != nil {
  43. fmt.Printf("GetUser err = %s \n", err)
  44. } else {
  45. name = user.Name
  46. Redis.Set(key, name, time.Second*10)
  47. }
  48. }
  49. return name
  50. }
  51. func GetModuleName(id int) string {
  52. var name string
  53. key := fmt.Sprintf(ModuleTypeKey, id)
  54. name, err := Redis.Get(key).Result()
  55. if err != nil {
  56. dict := &dao.Dict{Code: ModuleType, DictKey: strconv.Itoa(id)}
  57. if err := dict.GetByCodeAndKey(); err != nil {
  58. fmt.Printf("GetByCodeAndKey err = %d \n", err)
  59. } else {
  60. name = dict.DictValue
  61. Redis.Set(key, name, -1)
  62. }
  63. }
  64. return name
  65. }
  66. func GetControlType(id int) string {
  67. var name string
  68. key := fmt.Sprintf(ControlTypeKey, id)
  69. name, err := Redis.Get(key).Result()
  70. if err != nil {
  71. dict := &dao.Dict{Code: ControlType, DictKey: strconv.Itoa(id)}
  72. if err := dict.GetByCodeAndKey(); err != nil {
  73. fmt.Printf("GetByCodeAndKey err = %d \n", err)
  74. } else {
  75. name = dict.DictValue
  76. Redis.Set(key, name, -1)
  77. }
  78. }
  79. return name
  80. }