├── .gitignore ├── go.mod ├── go.sum └── main.go /.gitignore: -------------------------------------------------------------------------------- 1 | .idea -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module belajar-golang-kafka-producer 2 | 3 | go 1.21.5 4 | 5 | require github.com/confluentinc/confluent-kafka-go/v2 v2.3.0 // indirect 6 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/confluentinc/confluent-kafka-go/v2 v2.3.0 h1:icCHutJouWlQREayFwCc7lxDAhws08td+W3/gdqgZts= 2 | github.com/confluentinc/confluent-kafka-go/v2 v2.3.0/go.mod h1:/VTy8iEpe6mD9pkCH5BhijlUl8ulUXymKv1Qig5Rgb8= 3 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/confluentinc/confluent-kafka-go/v2/kafka" 6 | "strconv" 7 | ) 8 | 9 | func main() { 10 | config := &kafka.ConfigMap{ 11 | "bootstrap.servers": "localhost:9092", 12 | } 13 | 14 | producer, err := kafka.NewProducer(config) 15 | if err != nil { 16 | panic(err) 17 | } 18 | defer producer.Close() 19 | 20 | topic := "helloworld" 21 | 22 | for i := 0; i < 10; i++ { 23 | fmt.Printf("send message to kafka %d \n", i) 24 | 25 | key := strconv.Itoa(i) 26 | value := fmt.Sprintf("Hello %d", i) 27 | msg := &kafka.Message{ 28 | TopicPartition: kafka.TopicPartition{ 29 | Topic: &topic, 30 | Partition: kafka.PartitionAny, 31 | }, 32 | Key: []byte(key), 33 | Value: []byte(value), 34 | } 35 | 36 | err := producer.Produce(msg, nil) 37 | if err != nil { 38 | panic(err) 39 | } 40 | } 41 | 42 | producer.Flush(5 * 1000) 43 | } 44 | --------------------------------------------------------------------------------