forked from libi/dcron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
node_pool.go
83 lines (64 loc) · 1.62 KB
/
node_pool.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
package dcron
import (
"sync"
"github.com/bencen/dcron/consistenthash"
"github.com/bencen/dcron/driver"
"time"
)
const defaultReplicas = 50
const defaultDuration = 10
type NodePool struct {
serverName string
NodeId string
mu sync.Mutex
nodes *consistenthash.Map
Driver driver.Driver
opts PoolOptions
}
type PoolOptions struct {
Replicas int
HashFn consistenthash.Hash
}
func newNodePool(serverName,driverName string, dataSourceOption driver.DriverConnOpt) *NodePool{
nodePool := new(NodePool)
nodePool.Driver = driver.GetDriver(driverName)
nodePool.Driver.Open(dataSourceOption)
nodePool.serverName = serverName
option := PoolOptions{
Replicas:defaultReplicas,
}
nodePool.opts = option
nodePool.initPool()
go nodePool.tickerUpdatePool()
return nodePool
}
func (this *NodePool)initPool(){
this.Driver.SetTimeout(defaultDuration*time.Second)
this.NodeId = this.Driver.RegisterNode(this.serverName)
this.Driver.SetHeartBeat(this.NodeId)
this.updatePool()
}
func (this *NodePool)updatePool(){
this.mu.Lock()
defer this.mu.Unlock()
nodes := this.Driver.GetNodeList(this.serverName)
this.nodes = consistenthash.New(this.opts.Replicas, this.opts.HashFn)
for _, node := range nodes {
this.nodes.Add(node)
}
}
func(this *NodePool)tickerUpdatePool(){
tickers := time.NewTicker(time.Second * defaultDuration)
for range tickers.C {
this.updatePool()
}
}
//使用一致性hash算法根据任务名获取一个执行节点
func (this *NodePool) PickNodeByJobName(jobName string) string {
this.mu.Lock()
defer this.mu.Unlock()
if this.nodes.IsEmpty() {
return ""
}
return this.nodes.Get(jobName)
}