-
Notifications
You must be signed in to change notification settings - Fork 0
/
redis_producer.go
111 lines (89 loc) · 2.03 KB
/
redis_producer.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
package qmq
type RedisProducer struct {
connection *RedisConnection
config *RedisProducerConfig
channel chan interface{}
}
type RedisProducerConfig struct {
Topic string
Length int64
Transformers []Transformer
Distribution RedisProducerDistribution
}
type RedisProducerDistribution int64
const (
Duplicate RedisProducerDistribution = iota
RoundRobin
)
func NewRedisProducer(connection *RedisConnection, config *RedisProducerConfig) Producer {
if config.Length <= 0 {
config.Length = 10
}
producer := &RedisProducer{
connection: connection,
config: config,
channel: make(chan interface{}),
}
go producer.Process()
return producer
}
func (p *RedisProducer) Push(i interface{}) {
p.channel <- i
}
func (p *RedisProducer) Close() {
close(p.channel)
}
func (p *RedisProducer) Process() {
p.connection.WgAdd()
defer p.connection.WgDone()
queues := map[string]bool{}
pushToStream := func(s *RedisStream, m *Message) {
s.Locker.Lock()
defer s.Locker.Unlock()
p.connection.StreamAdd(s, m)
}
push := func(i interface{}) {
for _, transformer := range p.config.Transformers {
i = transformer.Transform(i)
if i == nil {
return
}
}
m, ok := i.(*Message)
if !ok {
return
}
s := NewRedisStream(p.config.Topic, p.connection)
s.Length = p.config.Length
pushToStream(s, m)
switch p.config.Distribution {
case Duplicate:
for q := range p.connection.StreamScan(p.config.Topic + ":*") {
if q == p.config.Topic {
continue
}
s = NewRedisStream(q, p.connection)
s.Length = p.config.Length
pushToStream(s, m)
}
case RoundRobin:
scanned := p.connection.StreamScan(p.config.Topic + ":*")
queues[p.config.Topic] = true
for q := range scanned {
if _, ok := queues[q]; !ok {
queues[q] = true
s = NewRedisStream(q, p.connection)
s.Length = p.config.Length
pushToStream(s, m)
break
}
}
if len(queues) == len(scanned) {
queues = map[string]bool{}
}
}
}
for i := range p.channel {
push(i)
}
}