配置文件:redis_config.ini
[default_redis_read] host = 192.168.1.xxx:6379 password = xxxxx max_idle = 50 max_active = 100 idle_timeout = 20 [default_redis_write] host = 192.168.1.235:6379 password = xxx max_idle = 50 max_active = 100 idle_timeout = 20 [api_redis] host = 192.168.1.235:6379 password = xxx max_idle = 50 max_active = 100 idle_timeout = 20
自定义多个redis链接
package config type RedisDatabase struct { Password string Host string Database string MaxIdle string MaxActive string MaxAIdleTimeoutctive string Prefix string } //多数据库配置 func BuildRedisConfgs() (RedisDatabaseMap map[string]RedisDatabase) { return map[string]RedisDatabase{ "search_r": { Host: Get("default_redis_read.host").String(), Password: Get("default_redis_read.password").String(), MaxIdle: Get("default_redis_read.max_idle").String(), MaxActive: Get("default_redis_read.max_active").String(), }, "search_w": { Host: Get("default_redis_write.host").String(), Password: Get("default_redis_write.password").String(), MaxIdle: Get("default_redis_read.max_idle").String(), MaxActive: Get("default_redis_read.max_active").String(), }, "api_redis": { Host: Get("api_redis.host").String(), Password: Get("api_redis.password").String(), MaxIdle: Get("api_redis.max_idle").String(), MaxActive: Get("api_redis.max_active").String(), }, } }
redis连接池实现:
package gredis import ( "github.com/gomodule/redigo/redis" "search_server/pkg/config" "time" ) type ichuntRedis struct { RedisList map[string]*redis.Pool } var ichuntRedis_ = &ichuntRedis{} func Conn(connection string) (redis.Conn){ return ichuntRedis_.RedisList[connection].Get() } var writeConn, readConn *redis.Pool func Setup() (err error) { ichuntRedis_.RedisList = make(map[string]*redis.Pool,0) RedisDatabaseMap := config.BuildRedisConfgs() for redisKey,redisConfig := range RedisDatabaseMap{ ichuntRedis_.RedisList[redisKey],err = getConn(redisConfig.Host, redisConfig.Password) if err != nil{ panic(err) } } return nil } //格式化成字符串 func String( a interface{},err error) (string,error) { return redis.String(a,err) } func getConn(writeHost, password string) (pool *redis.Pool, err error) { maxIdle, _ := config.Get("redis.max_idle").Int() maxActive, _ := config.Get("redis.max_active").Int() pool = &redis.Pool{ MaxIdle: maxIdle, MaxActive: maxActive, Dial: func() (redis.Conn, error) { c, err := redis.Dial("tcp", writeHost) if err != nil { return nil, err } if password != "" { if _, err := c.Do("AUTH", password); err != nil { c.Close() return nil, err } } return c, err }, TestOnBorrow: func(c redis.Conn, t time.Time) error { _, err := c.Do("PING") return err }, } return }
调用方式:
redisConn :=gredis.Conn("search_r") defer func(){ redisConn.Close() }()
本文来自博客园,作者:孙龙-程序员,转载请注明原文链接:https://www.cnblogs.com/sunlong88/p/13389712.html