Golang 推送消息到 kafka(生产者)

Jackey Golang 4,234 次浏览 , 2条评论

配置相关依赖包:

  1. mkdir -p $GOPATH/src/golang.org/x
  2. cd $GOPATH/src/golang.org/x
  3. git clone https://github.com/golang/net.git
  4. git clone https://github.com/golang/crypto.git
  5. go get github.com/Shopify/sarama

 

写入信息到 kafka

  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "github.com/Shopify/sarama"
  6. "time"
  7. )
  8.  
  9. func main() {
  10. //初始化配置
  11. config := sarama.NewConfig()
  12. config.Producer.RequiredAcks = sarama.WaitForAll
  13. config.Producer.Partitioner = sarama.NewRandomPartitioner
  14. config.Producer.Return.Successes = true
  15. //生产者
  16. client, err := sarama.NewSyncProducer([]string{"127.0.0.1:9092"}, config)
  17. if err != nil {
  18. fmt.Println("producer close,err:", err)
  19. return
  20. }
  21.  
  22. defer client.Close()
  23.  
  24. var n int=0
  25. for n<20{
  26. n++
  27. //创建消息
  28. msg := &sarama.ProducerMessage{}
  29. msg.Topic = "topic_title"
  30. msg.Value = sarama.StringEncoder("this is a good test,hello gopher.cc!!")
  31. //发送消息
  32. pid, offset, err := client.SendMessage(msg)
  33. if err != nil {
  34. fmt.Println("send message failed,", err)
  35. return
  36. }
  37. fmt.Printf("pid:%v offset:%v\n,", pid, offset)
  38. time.Sleep(10 * time.Millisecond)
  39. }
  40. }

2 条评论

  1. lalala 2019年10月30日 下午2:04 回复

    杰哥,猜猜我是谁~

    • PHP二次开发 2020年1月8日 上午11:23 回复

      猜不到哦

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Go