go操作kafka
-
ZooKeeper是一个分布式协调服务,它的主要作用是为分布式系统提供一致性服务,提供的功能包括:配置维护、命名服务、分布式同步、组服务等。Kafka的运行依赖ZooKeeper。目前kafka3.2.0以上版本(kafka_2.13-3.2.0.tgz)内就包含自带的ZooKeeper,因此直接下载Kafka就行。
-
解压Kafka压缩包,放到常用的目录下。打开终端,cd进入到kafka_2.13-3.2.0根目录下。
-
由于Kafka的运行依赖ZooKeeper,首先得运行zookeeper,并在后台挂载。
.\bin\windows\zookeeper-server-start.bat .\config\zookeeper.properties
-
开启kafka
.\bin\windows\kafka-server-start.bat .\config\server.properties
-
生产者代码:
package main import ( "fmt" "github.com/Shopify/sarama" ) // 基于sarama第三方库开发的kafka client func main() { config := sarama.NewConfig() config.Producer.RequiredAcks = sarama.WaitForAll // 发送完数据需要leader和follow都确认 config.Producer.Partitioner = sarama.NewRandomPartitioner // 新选出一个partition config.Producer.Return.Successes = true // 成功交付的消息将在success channel返回 // 构造一个消息 msg := &sarama.ProducerMessage{} msg.Topic = "web_log" msg.Value = sarama.StringEncoder("hhhhhhhh啦啦啦") // 连接kafka client, err := sarama.NewSyncProducer([]string{"127.0.0.1:9092"}, config) if err != nil { fmt.Println("producer closed, err:", err) return } defer client.Close() // 发送消息 pid, offset, err := client.SendMessage(msg) if err != nil { fmt.Println("send msg failed, err:", err) return } fmt.Printf("pid:%v offset:%v\n", pid, offset) }
-
消费者代码:
package main import ( "fmt" "github.com/Shopify/sarama" "sync" ) func consumer() { var wg sync.WaitGroup consumer, err := sarama.NewConsumer([]string{"127.0.0.1:9092"}, nil) if err != nil { fmt.Println("Failed to start consumer: %s", err) return } partitionList, err := consumer.Partitions("web_log") //获得该topic所有的分区 if err != nil { fmt.Println("Failed to get the list of partition:, ", err) return } for partition := range partitionList { pc, err := consumer.ConsumePartition("web_log", int32(partition), sarama.OffsetNewest) if err != nil { fmt.Println("Failed to start consumer for partition %d: %s\n", partition, err) return } wg.Add(1) fmt.Println(pc.Messages()) go func(sarama.PartitionConsumer) { //为每个分区开一个go协程去取值 // OffsetNewest从最新的地方开始 ,OffsetOldest是从头开始,一般选择OffsetNewest for msg := range pc.Messages() { //阻塞直到有值发送过来,然后再继续等待 fmt.Printf("Partition:%d, Offset:%d, key:%s, value:%s\n", msg.Partition, msg.Offset, string(msg.Key), string(msg.Value)) } defer pc.AsyncClose() wg.Done() }(pc) } wg.Wait() } func main() { consumer() }
标签:err,sarama,fmt,kafka,msg,go,操作,config From: https://www.cnblogs.com/luoyingfenfei/p/17595602.html