In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.