Redis Pipelines and Transactions with Golang

Alok Singhal
Mar 9 · 3 min read
import (
"github.com/gomodule/redigo/redis"
"time"
)

type RedisCache struct {
pool *redis.Pool
}

var (
// Pool :
pool
*redis.Pool
RedisCacheClient *RedisCache
)

func init() {
pool = newPool(<host>, "")
RedisCacheClient = &RedisCache{pool: pool}
}
func newPool(server string, password string) *redis.Pool {
return &redis.Pool{
MaxIdle: 3,
MaxActive: 200,
IdleTimeout: 240 * time.Second,
Wait: true,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", server, redis.DialPassword(password),
redis.DialReadTimeout(5000*time.Millisecond), redis.DialWriteTimeout(5000*time.Millisecond), redis.DialDatabase(10))
if err != nil {
return nil, err
}
return c, nil
},

TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
}
}
conn := RedisCacheClient.pool.Get()
defer conn.Close()
//write all commands to connection's output buffer
conn.Send("SET", "foo1","bar1")
conn.Send("SET", "foo2", "bar2")
conn.Send("GET", "foo3")
//flush output buffer to server
conn.Flush()
//receive replies one by one reply1, err1 := conn.Receive()
reply2, err2 := conn.Receive()
reply3, err3 := conn.Receive()
conn := RedisCacheClient.pool.Get()
defer conn.Close()
//start transaction
conn.Send("MULTI")
//add commands to the output buffer
conn.Send("INCR" , "foo1")
conn.Send("INCR", "foo2")
conn.Send("GET", "foo1")
//Flush all the commands to output buffer and read replies
reply, err := conn.Do("EXEC")

Alok Singhal

Written by

I have too many opinions

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade