/
watcher.go
96 lines (85 loc) · 1.61 KB
/
watcher.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/**
* @Time : 2019-07-16 10:36
* @Author : ygqbasic@gmail.com
* @File : redis
* @Software: VS Code
*/
package redis
import (
"errors"
"fmt"
"github.com/casbin/casbin/persist"
"github.com/go-redis/redis"
kplrds "github.com/fuhsicloud/fuhsicloud/src/redis"
"sync"
)
type Watcher struct {
rds kplrds.RedisInterface
callback func(string)
closed chan struct{}
once sync.Once
channel string
}
func NewWatcher(rds kplrds.RedisInterface) (persist.Watcher, error) {
watcher := &Watcher{
closed: make(chan struct{}),
channel: "/casbin",
rds: rds,
}
go func() {
for {
select {
case <-watcher.closed:
return
default:
err := watcher.subscribe()
if err != nil {
watcher.Close()
fmt.Printf("Failure from Redis subscription: %v", err)
}
}
}
}()
return watcher, nil
}
func (c *Watcher) SetUpdateCallback(callback func(string)) error {
c.callback = callback
return nil
}
func (c *Watcher) subscribe() error {
pubSub := c.rds.Subscribe(c.channel)
defer func() {
_ = pubSub.Close()
}()
for {
if pubSub == nil {
return errors.New("pubSub is nil")
}
n, err := pubSub.Receive()
if err != nil {
return err
}
switch n.(type) {
case *redis.Message:
if c.callback != nil {
c.callback(n.(*redis.Message).String())
}
case *redis.Subscription:
if n.(*redis.Subscription).Count == 0 {
return nil
}
}
}
}
func (c *Watcher) Update() error {
if err := c.rds.Publish(c.channel, "update rules"); err != nil {
return err
}
return nil
}
func (c *Watcher) Close() {
c.once.Do(func() {
close(c.closed)
})
//_ = c.rds.Close()
}