A little pit analysis of PubSub in redigo
Preface
Recently, I have been using golang to do some redis-related operations, choosing redigo as a third-party library. Then when I was using Pub/Sub, I found a small hole.
Redis Client
First, let's initialize a Redis Client with connection pooling:
Import ("github.com/gomodule/redigo/redis") type RedisClient struct {pool * redis.Pool} func NewRedisClient (addr string, db int, passwd string) * RedisClient {pool: = & redis.Pool {MaxIdle: 10, IdleTimeout: 300 * time.Second, Dial: func () (redis.Conn, error) {c Err: = redis.Dial ("tcp", addr, redis.DialPassword (passwd), redis.DialDatabase (db)) if err! = nil {return nil, err} return c, nil}, TestOnBorrow: func (c redis.Conn T time.Time) error {if time.Since (t) < time.Minute {return nil} _, err: = c.Do ("PING") return err} } log.Printf ("new redis pool at% s", addr) client: = & RedisClient {pool: pool,} return client}
Publish
Then we can simply implement a publish method:
Func (r * RedisClient) Publish (channel, message string) (int, error) {c: = r.pool.Get () defer c.Close () n, err: = redis.Int (c.Do ("PUBLISH", channel, message) if err! = nil {return 0, fmt.Errorf ("redis publish% s% s, err:% v", channel, message, err)} return n, nil}
Subscribe
Then there is a slightly more complex subscribe method with a heartbeat:
Func (r * RedisClient) Subscribe (ctx context.Context, consume ConsumeFunc, channel... string) error {psc: = redis.PubSubConn {Conn: r.pool.Get ()} defer psc.Close () log.Printf ("redis pubsub subscribe channel:% v", channel) if err: = psc.Subscribe (redis.Args {} .AddFlat (channel)...) Err! = nil {return err} done: = make (chan error, 1) / / start a new goroutine to receive message go func () {for {switch msg: = psc.Receive (). (type) {case error: done