-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
79 lines (69 loc) · 1.46 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
package main
import (
"context"
"encoding/json"
"log"
"math/rand"
"os"
"os/signal"
"syscall"
"time"
)
type Order struct {
Date time.Time `json:"date"`
Items []string `json:"items"`
Payment string `json:"payment"`
Price float64 `json:"price"`
}
func main() {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
cancelChan := make(chan os.Signal)
signal.Notify(cancelChan, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
p, err := NewProducer("localhost:9092", "ORDERS")
if err != nil {
log.Fatal("cannot create producer: ", err)
}
c, err := NewConsumer("localhost:9092", "ORDER-PROCESSING-SERVICE")
if err != nil {
log.Fatal("cannot create order processing consumer: ", err)
}
// Produce
go func(ctx context.Context) {
for {
time.Sleep(time.Second)
order := Order{
Date: time.Now(),
Items: []string{"macbook", "iPhone", "iMac"},
Payment: "CREDIT_CARD",
Price: rand.Float64() * 25000,
}
valBytes, err := json.Marshal(&order)
if err != nil {
log.Fatal("cannot json marshal value: ", order)
cancel()
}
_, err = p.Send("user.1", valBytes)
if err != nil {
log.Fatal("cannot send message to broker: ", err)
cancel()
}
}
}(ctx)
// Receive
go func(ctx context.Context) {
err := c.Listen([]string{"ORDERS"})
if err != nil {
log.Fatal(err)
cancel()
}
}(ctx)
for {
select {
case <-cancelChan:
cancel()
case <-ctx.Done():
os.Exit(1)
}
}
}