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"
|
"context"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/go-redis/redis/v8"
|
"github.com/redis/go-redis/v9"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@ -23,6 +23,10 @@ type Redis struct {
|
|||||||
separator string // 分隔符
|
separator string // 分隔符
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type Subscriber struct {
|
||||||
|
*redis.PubSub
|
||||||
|
}
|
||||||
|
|
||||||
func New(addr string, opts ...Option) *Redis {
|
func New(addr string, opts ...Option) *Redis {
|
||||||
r := &Redis{
|
r := &Redis{
|
||||||
addr: addr,
|
addr: addr,
|
||||||
@ -74,6 +78,29 @@ func (s *Redis) Del(ctx context.Context, key ...string) (int, error) {
|
|||||||
return int(v), err
|
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) {
|
func (s *Redis) getRedis() (redis.UniversalClient, error) {
|
||||||
client := redis.NewUniversalClient(&redis.UniversalOptions{
|
client := redis.NewUniversalClient(&redis.UniversalOptions{
|
||||||
Addrs: []string{s.addr},
|
Addrs: []string{s.addr},
|
||||||
|
Reference in New Issue
Block a user