forked from elastic/go-elasticsearch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproducer.go
187 lines (161 loc) · 3.84 KB
/
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
// Licensed to Elasticsearch B.V. under one or more agreements.
// Elasticsearch B.V. licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
package producer
import (
"bytes"
"context"
"fmt"
"math/rand"
"net"
"time"
"github.com/segmentio/kafka-go"
)
var (
sides = []string{"BUY", "SELL"}
symbols = []string{"KBCU", "KBCU", "KBCU", "KJPR", "KJPR", "KSJD", "KXCV", "WRHV", "WTJB", "WMLU"}
accounts = []string{"ABC123", "ABC123", "ABC123", "LMN456", "LMN456", "STU789"}
)
func init() {
rand.Seed(time.Now().UnixNano())
kafka.DefaultClientID = "go-elasticsearch-kafka-demo"
}
type Producer struct {
BrokerURL string
TopicName string
TopicParts int
MessageRate int
writer *kafka.Writer
startTime time.Time
totalMessages int64
totalErrors int64
totalBytes int64
}
func (p *Producer) Run(ctx context.Context) error {
var messages []kafka.Message
p.startTime = time.Now()
p.writer = kafka.NewWriter(kafka.WriterConfig{
Brokers: []string{p.BrokerURL},
Topic: p.TopicName,
})
ticker := time.NewTicker(time.Second)
for {
select {
case t := <-ticker.C:
for i := 1; i <= p.MessageRate; i++ {
messages = append(messages, kafka.Message{Value: p.generateMessage(t)})
}
if err := p.writer.WriteMessages(ctx, messages...); err != nil {
messages = messages[:0]
return err
}
messages = messages[:0]
}
}
p.writer.Close()
ticker.Stop()
return nil
}
func (p *Producer) CreateTopic(ctx context.Context) error {
conn, err := net.Dial("tcp", p.BrokerURL)
if err != nil {
return err
}
return kafka.NewConn(conn, "", 0).CreateTopics(
kafka.TopicConfig{
Topic: p.TopicName,
NumPartitions: p.TopicParts,
ReplicationFactor: 1,
})
}
func (p *Producer) generateMessage(t time.Time) []byte {
var (
buf bytes.Buffer
timestamp time.Time
timeshift time.Duration
side string
quantity int
price int
amount int
symbol string
account string
)
timestamp = t
if timestamp.Minute() == 2 {
timeshift = -(time.Duration(time.Minute))
} else {
timeshift = time.Duration(time.Duration(rand.ExpFloat64()/2.0*100) * time.Second)
}
switch {
case timestamp.Minute()%5 == 0:
side = "SELL"
default:
if timestamp.Second()%3 == 0 {
side = "SELL"
} else {
side = "BUY"
}
}
switch {
case timestamp.Minute()%3 == 0:
quantity = rand.Intn(250) + 500
case timestamp.Second()%6 == 0:
quantity = rand.Intn(300) + 50
case timestamp.Second()%12 == 0:
quantity = rand.Intn(10) + 1
default:
quantity = rand.Intn(150) + 10
}
if side == "SELL" {
price = int(100.0 + 15.0*rand.NormFloat64())
} else {
price = int(250.0 + 50.0*rand.NormFloat64())
}
amount = quantity * price
if timestamp.Second()%4 == 0 {
symbol = "KXCV"
} else {
symbol = symbols[rand.Intn(len(symbols))]
}
if timestamp.Minute()%5 == 0 && timestamp.Second() > 30 {
account = "STU789"
} else {
account = accounts[rand.Intn(len(accounts))]
}
fmt.Fprintf(&buf,
`{"time":"%s", "symbol":"%s", "side":"%s", "quantity":%d, "price":%d, "amount":%d, "account":"%s"}`,
timestamp.UTC().Add(timeshift).Format(time.RFC3339),
symbol,
side,
quantity,
price,
amount,
account,
)
return buf.Bytes()
}
type Stats struct {
Duration time.Duration
TotalMessages int64
TotalErrors int64
TotalBytes int64
Throughput float64
}
func (p *Producer) Stats() Stats {
if p.writer == nil {
return Stats{}
}
duration := time.Since(p.startTime)
writerStats := p.writer.Stats()
p.totalMessages += writerStats.Messages
p.totalErrors += writerStats.Errors
p.totalBytes += writerStats.Bytes
rate := float64(p.totalMessages) / duration.Seconds()
return Stats{
Duration: duration,
TotalMessages: p.totalMessages,
TotalErrors: p.totalErrors,
TotalBytes: p.totalBytes,
Throughput: rate,
}
}