/
redis_producer.go
73 lines (55 loc) · 1.31 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
package qmq
type RedisProducer struct {
connection *RedisConnection
stream *RedisStream
transformers []Transformer
channel chan interface{}
}
func NewRedisProducer(key string, connection *RedisConnection, length int64, transformers []Transformer) Producer {
producer := &RedisProducer{
connection: connection,
stream: NewRedisStream(key, connection),
transformers: transformers,
channel: make(chan interface{}),
}
producer.Initialize(length)
return producer
}
func (p *RedisProducer) Initialize(length int64) {
p.stream.Locker.Lock()
defer p.stream.Locker.Unlock()
readRequest, err := p.connection.Get(p.stream.ContextKey())
if err == nil {
readRequest.Data.UnmarshalTo(&p.stream.Context)
}
p.stream.Length = length
go p.Process()
}
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()
push := func(i interface{}) {
p.stream.Locker.Lock()
defer p.stream.Locker.Unlock()
for _, transformer := range p.transformers {
i = transformer.Transform(i)
if i == nil {
return
}
}
m, ok := i.(*Message)
if !ok {
return
}
p.connection.StreamAdd(p.stream, m)
}
for i := range p.channel {
push(i)
}
}