package common import ( "context" "fmt" "github.com/go-redis/redis/v8" "log" "os" "time" "github.com/spf13/viper" _ "github.com/spf13/viper/remote" "gorm.io/driver/mysql" "gorm.io/gorm" "gorm.io/gorm/logger" ) func GetConsulConfig(url string, fileKey string) (*viper.Viper, error) { conf := viper.New() conf.AddRemoteProvider("consul", url, fileKey) conf.SetConfigType("json") err := conf.ReadRemoteConfig() if err != nil { log.Println("viper conf err :", err) //}else { //log.Println("viper conf :", conf) } return conf, nil } /** { "host": "192.168.137.131", "port": "3306", "user": "root", "pwd": "mashibing123", "database": "user_center" } **/ // type MySQLConfig struct { // Host string `json:"host"` // Post string `json:"port"` // User string `json:"user"` // Pwd string `json:"pwd"` // Database string `json:"database"` // } // // 获取 MySQL配置 func GetMysqlFromConsul(vip *viper.Viper) (db *gorm.DB, err error) { newLogger := logger.New( log.New(os.Stdout, "\r\n", log.LstdFlags), logger.Config{ SlowThreshold: time.Second, LogLevel: logger.Info, Colorful: true, }, ) str := vip.GetString("user") + ":" + vip.GetString("pwd") + "@tcp(" + vip.GetString("host") + ":" + vip.GetString("port") + ")/" + vip.GetString("database") + "?charset=utf8mb4&parseTime=True&loc=Local" db, errr := gorm.Open(mysql.Open(str), &gorm.Config{Logger: newLogger}) //"root:mashibing123@tcp(8.142.25.43:3306)/user_center?charset=utf8mb4&parseTime=True&loc=Local"), &gorm.Config{Logger: newLogger}) if errr != nil { log.Println("db err :", errr) } return db, nil } /** { "addr": "192.168.100.131", "password": "", "DB": "0", "poolSize": "30", "minIdleConn": "30" } */ // 获取redis 配置 func GetRedisFromConsul(vip *viper.Viper) (red *redis.Client, err error) { red = redis.NewClient(&redis.Options{ Addr: vip.GetString("addr"), Password: vip.GetString("password"), DB: vip.GetInt("DB"), PoolSize: vip.GetInt("poolSize"), MinIdleConns: vip.GetInt("minIdleConn"), }) //集群 clusterClients := redis.NewClusterClient( &redis.ClusterOptions{ Addrs: []string{"192.168.100.131:6380", "192.168.100.131:6381", "192.168.100.131:6382"}, }) fmt.Println(clusterClients) return red, nil } // 设置用户登录信息 func SetUserToken(red *redis.Client, key string, val []byte, timeTTL time.Duration) { red.Set(context.Background(), key, val, timeTTL) } // 获取用户登录信息 func GetUserToken(red *redis.Client, key string) string { res, err := red.Get(context.Background(), key).Result() if err != nil { log.Print("GetUserToken err ", err) } return res }