Go语言与Docker操作Redis

Python027

Go语言与Docker操作Redis,第1张

首选,如果之前使用过redis容器,我们需要先remove掉之前的容器

然后创建redis容器,并运行

进入redis容器中

接着我们通过 redis-cli 连接测试使用 redis 服务

setex指令 可以设置数据存在的时间, setex key second value

MSET 一次设置多个key-value

MGET一次获取多个key-value

HGET

HGETALL

Hlen和hexist

Lpush 和 Lrange

Lpop和Rpop 从链表取出并移走数据

删除链表所有数据 DEL

字符串无序 不能重复

连接池中Get出一个conn连接

1.在创建连接池之后,起一个 go routine,每隔一段 idleTime 发送一个 PING 到 Redis server。其中,idleTime 略小于 Redis server 的 timeout 配置。

2.连接池初始化部分代码如下:

p, err := pool.New("tcp", u.Host, concurrency) errHndlr(err) go func() { for { p.Cmd("PING") time.Sleep(idelTime * time.Second) } }()

3.使用 redis 传输数据部分代码如下:

func redisDo(p *pool.Pool, cmd string, args ...interface{}) (reply *redis.Resp, err error) { reply = p.Cmd(cmd, args...) if err = reply.Errerr != nil { if err != io.EOF { Fatal.Println("redis", cmd, args, "err is", err) } } return }

4.其中,Radix.v2 连接池内部进行了连接池内连接的获取和放回,代码如下:

// Cmd automatically gets one client from the pool, executes the given command // (returning its result), and puts the client back in the pool func (p *Pool) Cmd(cmd string, args ...interface{}) *redis.Resp { c, err := p.Get() if err != nil { return redis.NewResp(err) } defer p.Put(c) return c.Cmd(cmd, args...) }

这样,就有了系统 keep alive 的机制,不会出现 time out 的连接了,从 redis 连接池里面取出的连接都是可用的连接了。看似简单的代码,却完美的解决了连接池里面超时连接的问题。同时,就算 Redis server 重启等情况,也能保证连接自动重连。