本地服务链接远程redis服务器时,往往需要远程redis服务允许远程链接,修改
redis
配置如下
修改redis服务器的配置文件
- 打开redis.server配置文件,修改如下配置
//关闭本地监听或者改为0.0.0.0
# bind 127.0.0.1
//保护模式
protected-mode no
//去掉 # 号变requirepass foobared ,注:foobared是密码;
#requirepass foobared
- 重启redis
- 将6379端口暴露出去
iptables -I INPUT 1 -p tcp -m state --state NEW -m tcp --dport 6379 -j ACCEPT
配置reidgo连接池
下载redigo
go get github.com/garyburd/redigo/redis
官方手册https://godoc.org/github.com/garyburd/redigo/redis
func RedisPool() *redis.Pool {
return &redis.Pool{
MaxIdle: 3,//最大空闲数
MaxActive:100,//最大活跃数
IdleTimeout: 240 * time.Second,//最大的空闲连接等待时间,超过此时间后,空闲连接将被关闭
Dial: func () (redis.Conn, error) {
//此处对应redis ip及端口号
conn, err := redis.Dial("tcp", "127.0.0.1:6379")
if err != nil {
return nil, err
}
//此处1234对应redis密码
if _, err := conn.Do("AUTH", "123456"); err != nil {
conn.Close()
return nil, err
}
return conn,err
},
}
}
使用连接池
redisPool := RedisPool()
defer redisPool.Close()
conn := redisPool.Get()
str, err := redis.String(conn.Do("get", "name"))
//返回的是对应的字符切片
fmt.Println(str)
//gangan
redis 提供了相关的将interface转换为其他类型的数据的方法,参考如下
func Bool(reply interface{}, err error) (bool, error)
func Bytes(reply interface{}, err error) ([]byte, error)
func Float64(reply interface{}, err error) (float64, error)
func Int(reply interface{}, err error) (int, error)
func Int64(reply interface{}, err error) (int64, error)
func String(reply interface{}, err error) (string, error)
func Strings(reply interface{}, err error) ([]string, error)
func Uint64(reply interface{}, err error) (uint64, error)