Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

A little pit analysis of PubSub in redigo

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report