From 165fc91f9b88e27655ba9bca3cf140ce7d2a1f52 Mon Sep 17 00:00:00 2001 From: charlie <3140647@qq.com> Date: Thu, 12 Oct 2023 14:29:42 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E8=AE=A2=E9=98=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- redis/redis.go | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/redis/redis.go b/redis/redis.go index ea5fd3b..c0e3fa6 100644 --- a/redis/redis.go +++ b/redis/redis.go @@ -4,7 +4,7 @@ import ( "context" "time" - "github.com/go-redis/redis/v8" + "github.com/redis/go-redis/v9" ) const ( @@ -23,6 +23,10 @@ type Redis struct { separator string // 分隔符 } +type Subscriber struct { + *redis.PubSub +} + func New(addr string, opts ...Option) *Redis { r := &Redis{ addr: addr, @@ -74,6 +78,29 @@ func (s *Redis) Del(ctx context.Context, key ...string) (int, error) { return int(v), err } +func (s *Redis) Subscribe(ctx context.Context, channel string) Subscriber { + conn, err := s.getRedis() + if err != nil { + return Subscriber{} + } + + sub := conn.Subscribe(context.Background(), channel) + + return Subscriber{sub} +} + +func (s *Redis) Publish(ctx context.Context, channel, msg string) *redis.IntCmd { + + conn, err := s.getRedis() + if err != nil { + return &redis.IntCmd{} + } + + cmd := conn.Publish(ctx, channel, msg) + + return cmd +} + func (s *Redis) getRedis() (redis.UniversalClient, error) { client := redis.NewUniversalClient(&redis.UniversalOptions{ Addrs: []string{s.addr},