package util import ( "fmt" "github.com/go-redis/redis" "iot_manager_service/app/device/dao" dao2 "iot_manager_service/app/user/dao" "iot_manager_service/config" "strconv" "time" ) var Redis *redis.Client func InitRedis() error { cfg := config.Instance() addr := cfg.Redis.Host Redis = redis.NewClient(&redis.Options{ Addr: addr, DialTimeout: 10 * time.Second, ReadTimeout: 30 * time.Second, WriteTimeout: 30 * time.Second, PoolSize: 10, PoolTimeout: 30 * time.Second, }) _, err := Redis.Ping().Result() if err != nil { return err } return nil } const ( UserKey = "user_%d" ModuleTypeKey = "module_type_%d" ControlTypeKey = "control_type_%d" ControlType = "control_type" ModuleType = "module_his_type" ) func GetUserName(id int64) string { var name string key := fmt.Sprintf(UserKey, id) name, err := Redis.Get(key).Result() if err != nil { user := &dao2.User{ID: id} if err := user.GetUser(); err != nil { fmt.Printf("GetUser err = %s \n", err) } else { name = user.Name Redis.Set(key, name, time.Second*10) } } return name } func GetModuleName(id int) string { var name string key := fmt.Sprintf(ModuleTypeKey, id) name, err := Redis.Get(key).Result() if err != nil { dict := &dao.Dict{Code: ModuleType, DictKey: strconv.Itoa(id)} if err := dict.GetByCodeAndKey(); err != nil { fmt.Printf("GetByCodeAndKey err = %d \n", err) } else { name = dict.DictValue Redis.Set(key, name, -1) } } return name } func GetControlType(id int) string { var name string key := fmt.Sprintf(ControlTypeKey, id) name, err := Redis.Get(key).Result() if err != nil { dict := &dao.Dict{Code: ControlType, DictKey: strconv.Itoa(id)} if err := dict.GetByCodeAndKey(); err != nil { fmt.Printf("GetByCodeAndKey err = %d \n", err) } else { name = dict.DictValue Redis.Set(key, name, -1) } } return name }