-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsiq_observer.go
85 lines (67 loc) · 1.35 KB
/
siq_observer.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
package siq
import (
"errors"
"fmt"
"math/rand"
)
func StartSiq() []*Siq{
so := newObserver(2)
so.start()
return so.siqList
}
type SiqObserver struct {
siqList []*Siq
topicMap map[string]*Siq
backupMap map[string]*Siq
}
func newObserver(siqCount int) *SiqObserver {
so := &SiqObserver{
siqList: []*Siq{},
topicMap: map[string]*Siq{},
backupMap: map[string]*Siq{},
}
for i :=0; i < siqCount; i++ {
so.siqList = append(so.siqList, newSiq(so))
}
return so
}
func(so *SiqObserver) start() {
for _, s := range(so.siqList) {
s.Start()
}
}
func(so *SiqObserver) GetSiqByTopic(t string) *Siq {
return so.topicMap[t]
}
func(so *SiqObserver) GetBackupSiqByTopic(t string) *Siq {
s, ok := so.backupMap[t]
if ok {
return s
}
s = so.electBackupSiq(t)
return s
}
func(so *SiqObserver) SetSiqTopic(t string, s *Siq) error {
if _, exists := so.topicMap[t]; exists {
return errors.New(fmt.Sprintf("topic already exists: %s", t))
}
so.topicMap[t] = s
so.electBackupSiq(t)
return nil
}
func (so *SiqObserver) electBackupSiq(t string) *Siq {
if len(so.siqList) < 2 {
return nil
}
mainSiq, ok := so.topicMap[t]
if ok == false {
return nil
}
i := rand.Intn(len(so.siqList))
backupSiq := so.siqList[i]
if mainSiq == backupSiq {
backupSiq = so.siqList[(i + 1) % len(so.siqList)]
}
so.backupMap[t] = backupSiq
return backupSiq
}