Get the App
SLTechnology News&Howtos  ›  Database  › 

A little pit analysis of PubSub in redigo

Shulou Source: shulou.com Published: 2022-06-01 03:02:31 11月27日 Update

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

Tags: The question that is the content that is the method the time the aspect the reference the learning the pit the difference the complexity the similarity and then the further that is value position function function. Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info Microsoft Docker vpn Shulou Technology