github.com/tuingking/flamingo@v0.0.0-20220403134817-2796ae0e84ca/cmd/producer/main.go (about) 1 package main 2 3 import ( 4 "context" 5 "fmt" 6 "math/rand" 7 "strconv" 8 "sync" 9 "time" 10 11 "github.com/pkg/errors" 12 "github.com/segmentio/kafka-go" 13 "github.com/sirupsen/logrus" 14 ) 15 16 const topic = "payment.success" 17 18 var wg sync.WaitGroup 19 20 func main() { 21 wg.Add(1) 22 23 //*** Producer 24 go func() { 25 spam(1_000_000) 26 wg.Done() 27 }() 28 29 wg.Wait() 30 } 31 32 func spam(n int64) { 33 w := kafka.NewWriter(kafka.WriterConfig{ 34 Brokers: []string{"localhost:9092"}, 35 Topic: topic, 36 Balancer: &kafka.Hash{}, 37 // Balancer: &kafka.LeastBytes{}, 38 }) 39 defer w.Close() 40 41 keys := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} 42 43 var count int64 44 for { 45 key := strconv.Itoa(keys[rand.Intn(10)]) 46 val := fmt.Sprintf("Product %d", count) 47 48 logrus.Infof("[SEND] %s:%s", key, val) 49 if err := w.WriteMessages(context.Background(), kafka.Message{ 50 Key: []byte(key), 51 Value: []byte(val), 52 }); err != nil { 53 logrus.Fatal(errors.Wrap(err, "failed to write message")) 54 } 55 56 time.Sleep(10 * time.Millisecond) 57 count++ 58 59 if count == n { 60 break 61 } 62 } 63 }