mirror of
https://github.com/charlienet/go-mixed.git
synced 2025-07-18 00:22:41 +08:00
添加订阅
This commit is contained in:
@ -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},
|
||||
|
Reference in New Issue
Block a user