-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrediszsetdriver.go
141 lines (128 loc) · 3.02 KB
/
rediszsetdriver.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
package redisdriver
import (
"context"
"errors"
"fmt"
"log"
"sync"
"time"
"github.com/dcron-contrib/commons"
"github.com/dcron-contrib/commons/dlog"
"github.com/redis/go-redis/v9"
)
type RedisZSetDriver struct {
c redis.UniversalClient
serviceName string
nodeID string
timeout time.Duration
logger dlog.Logger
started bool
// this context is used to define
// the lifetime of this driver.
runtimeCtx context.Context
runtimeCancel context.CancelFunc
sync.Mutex
}
func NewZSetDriver(redisClient redis.UniversalClient) *RedisZSetDriver {
rd := &RedisZSetDriver{
c: redisClient,
logger: &dlog.StdLogger{
Log: log.Default(),
},
timeout: redisDefaultTimeout,
}
rd.started = false
return rd
}
func (rd *RedisZSetDriver) Init(serviceName string, opts ...commons.Option) {
rd.serviceName = serviceName
rd.nodeID = commons.GetNodeId(serviceName)
for _, opt := range opts {
rd.WithOption(opt)
}
}
func (rd *RedisZSetDriver) NodeID() string {
return rd.nodeID
}
func (rd *RedisZSetDriver) GetNodes(ctx context.Context) (nodes []string, err error) {
rd.Lock()
defer rd.Unlock()
sliceCmd := rd.c.ZRangeByScore(ctx, commons.GetKeyPre(rd.serviceName), &redis.ZRangeBy{
Min: fmt.Sprintf("%d", commons.TimePre(time.Now(), rd.timeout)),
Max: "+inf",
})
if err = sliceCmd.Err(); err != nil {
return nil, err
} else {
nodes = make([]string, len(sliceCmd.Val()))
copy(nodes, sliceCmd.Val())
}
rd.logger.Infof("nodes=%v", nodes)
return
}
func (rd *RedisZSetDriver) Start(ctx context.Context) (err error) {
rd.Lock()
defer rd.Unlock()
if rd.started {
err = errors.New("this driver is started")
return
}
rd.runtimeCtx, rd.runtimeCancel = context.WithCancel(context.TODO())
rd.started = true
// register
err = rd.registerServiceNode()
if err != nil {
rd.logger.Errorf("register service error=%v", err)
return
}
// heartbeat timer
go rd.heartBeat()
return
}
func (rd *RedisZSetDriver) Stop(ctx context.Context) (err error) {
rd.Lock()
defer rd.Unlock()
rd.runtimeCancel()
rd.started = false
return
}
func (rd *RedisZSetDriver) WithOption(opt commons.Option) (err error) {
switch opt.Type() {
case commons.OptionTypeTimeout:
{
rd.timeout = opt.(commons.TimeoutOption).Timeout
}
case commons.OptionTypeLogger:
{
rd.logger = opt.(commons.LoggerOption).Logger
}
}
return
}
// private function
func (rd *RedisZSetDriver) heartBeat() {
tick := time.NewTicker(rd.timeout / 2)
for {
select {
case <-tick.C:
{
if err := rd.registerServiceNode(); err != nil {
rd.logger.Errorf("register service node error %+v", err)
}
}
case <-rd.runtimeCtx.Done():
{
if err := rd.c.Del(context.Background(), rd.nodeID, rd.nodeID).Err(); err != nil {
rd.logger.Errorf("unregister service node error %+v", err)
}
return
}
}
}
}
func (rd *RedisZSetDriver) registerServiceNode() error {
return rd.c.ZAdd(context.Background(), commons.GetKeyPre(rd.serviceName), redis.Z{
Score: float64(time.Now().Unix()),
Member: rd.nodeID,
}).Err()
}