-
Notifications
You must be signed in to change notification settings - Fork 415
/
Copy pathmain.go
110 lines (87 loc) · 2.25 KB
/
main.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
package main
import (
"encoding/json"
"fmt"
"math/rand"
"os"
"os/signal"
"sync"
"time"
"github.com/brianvoe/gofakeit/v6"
"github.com/ThreeDotsLabs/watermill"
"github.com/ThreeDotsLabs/watermill-kafka/v3/pkg/kafka"
"github.com/ThreeDotsLabs/watermill/message"
"github.com/ThreeDotsLabs/watermill/message/router/middleware"
)
var (
brokers = []string{"kafka:9092"}
messagesPerSecond = 100
numWorkers = 20
)
func main() {
logger := watermill.NewStdLogger(false, false)
logger.Info("Starting the producer", watermill.LogFields{})
publisher, err := kafka.NewPublisher(
kafka.PublisherConfig{
Brokers: brokers,
Marshaler: kafka.DefaultMarshaler{},
},
logger,
)
if err != nil {
panic(err)
}
defer publisher.Close()
closeCh := make(chan struct{})
workersGroup := &sync.WaitGroup{}
workersGroup.Add(numWorkers)
for i := 0; i < numWorkers; i++ {
go worker(publisher, workersGroup, closeCh)
}
// wait for SIGINT
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
<-c
// signal for the workers to stop publishing
close(closeCh)
// Waiting for all messages to be published
workersGroup.Wait()
logger.Info("All messages published", nil)
}
// worker publishes messages until closeCh is closed.
func worker(publisher message.Publisher, wg *sync.WaitGroup, closeCh chan struct{}) {
ticker := time.NewTicker(time.Duration(int(time.Second) / messagesPerSecond))
for {
select {
case <-closeCh:
ticker.Stop()
wg.Done()
return
case <-ticker.C:
}
msgPayload := postAdded{
OccurredOn: time.Now(),
Author: gofakeit.Username(),
Title: gofakeit.Sentence(rand.Intn(5) + 1),
Content: gofakeit.Sentence(rand.Intn(10) + 5),
}
payload, err := json.Marshal(msgPayload)
if err != nil {
panic(err)
}
msg := message.NewMessage(watermill.NewUUID(), payload)
// Use a middleware to set the correlation ID, it's useful for debugging
middleware.SetCorrelationID(watermill.NewShortUUID(), msg)
err = publisher.Publish("posts_published", msg)
if err != nil {
fmt.Println("cannot publish message:", err)
continue
}
}
}
type postAdded struct {
OccurredOn time.Time `json:"occurred_on"`
Author string `json:"author"`
Title string `json:"title"`
Content string `json:"content"`
}