-
Notifications
You must be signed in to change notification settings - Fork 1
/
cache_subscription.go
75 lines (60 loc) · 1.53 KB
/
cache_subscription.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package cache_lib
import (
"context"
"errors"
"github.com/go-redis/redis/v8"
)
type CacheSubscription interface {
Unsubscribe(ctx context.Context) error
UnsubscribeAndClose(ctx context.Context) error
Subscribe(ctx context.Context) CacheSubscription
GetChannel(ctx context.Context) (<-chan *redis.Message, error)
}
type cacheSubscription struct {
channel string
client *redis.Client
Subscription *redis.PubSub
}
func NewCacheSubscription(client *redis.Client, channel string) CacheSubscription {
return &cacheSubscription{
client: client,
channel: channel,
Subscription: nil,
}
}
func (cs *cacheSubscription) Unsubscribe(ctx context.Context) error {
if cs.Subscription == nil {
return nil
}
err := cs.Subscription.Unsubscribe(ctx, cs.channel)
if err != nil {
return err
}
cs.Subscription = nil
return nil
}
func (cs *cacheSubscription) UnsubscribeAndClose(ctx context.Context) error {
if cs.Subscription == nil {
return nil
}
err := cs.Subscription.Unsubscribe(ctx, cs.channel)
if err != nil {
return err
}
cs.Subscription.Close()
cs.Subscription = nil
return nil
}
func (cs *cacheSubscription) Subscribe(ctx context.Context) CacheSubscription {
cs.Subscription = cs.client.Subscribe(ctx, cs.channel)
if cs.Subscription == nil {
panic("no subscription created")
}
return cs
}
func (cs *cacheSubscription) GetChannel(ctx context.Context) (<-chan *redis.Message, error) {
if cs.Subscription == nil {
return nil, errors.New("No subscription")
}
return cs.Subscription.Channel(), nil
}