forked from acjzz/gokaf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
topic.go
70 lines (62 loc) · 1.38 KB
/
topic.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
package gokaf
import (
"context"
)
type Topic struct {
ctx context.Context
ctxCancel context.CancelFunc
logger LogWrapper
name string
channel chan internalMessage
consumers []*consumer
producer *producer
handler func(string, interface{})
}
func NewTopic(ctx context.Context, name string, handler func(string, interface{}), numConsumers ...int) *Topic {
var channelTopic chan internalMessage
if len(numConsumers) > 0 {
channelTopic = make(chan internalMessage, numConsumers[0])
} else {
channelTopic = make(chan internalMessage)
}
ctx = setTopicKey(ctx, name)
ctx, cancel := context.WithCancel(ctx)
logger := NewLogrusLogger(ctx, getLogFields)
t := &Topic{
ctx,
cancel,
logger,
name,
channelTopic,
[]*consumer{},
newProducer(ctx, &channelTopic),
handler,
}
if len(numConsumers) > 0 {
t.addConsumers(numConsumers[0])
} else {
t.addConsumer()
}
return t
}
func (t *Topic) stop() {
t.logger.Warn("stop")
t.ctxCancel()
}
func (t *Topic) addConsumer() {
ctx := setConsumerKey(t.ctx, len(t.consumers))
t.consumers = append(t.consumers, newConsumer(ctx, &t.channel, t.handler))
}
func (t *Topic) addConsumers(num int) {
for i := 0; i < num; i += 1 {
t.addConsumer()
}
}
func (t *Topic) publish(message internalMessage) error {
return t.producer.publish(message)
}
func (t *Topic) run() {
for _, c := range t.consumers {
c.run()
}
}