多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
> ### 生产者 ~~~ package main import ( "fmt" "time" "github.com/Shopify/sarama" ) func main() { config := sarama.NewConfig() config.Producer.RequiredAcks = sarama.WaitForAll config.Producer.Partitioner = sarama.NewRandomPartitioner config.Producer.Return.Successes = true client, err := sarama.NewSyncProducer([]string{"192.168.1.170:9092", "192.168.1.171:9092", "192.168.1.172:9092"}, config) if err != nil { fmt.Println("producer close, err:", err) return } defer client.Close() number := 1 for { msg := &sarama.ProducerMessage{} msg.Topic = "my-topic" msg.Value = sarama.StringEncoder(fmt.Sprint("this is a good test - ", number)) pid, offset, err := client.SendMessage(msg) if err != nil { fmt.Println("send message failed ", err) return } fmt.Printf("pid:%v offset:%v\n", pid, offset) time.Sleep(time.Second) number++ } } ~~~ > ### 消费者 ~~~ package main import ( "fmt" "sync" "github.com/Shopify/sarama" ) var ( wg sync.WaitGroup ) func main() { //创建消费者 consumer, err := sarama.NewConsumer([]string{"192.168.1.170:9092", "192.168.1.171:9092", "192.168.1.172:9092"}, nil) if err != nil { fmt.Println("Failed to start consumer: %s", err) return } //设置分区 partitionList, err := consumer.Partitions("my-topic") if err != nil { fmt.Println("Failed to get the list of partitions: ", err) return } fmt.Println(partitionList) //循环分区 for partition := range partitionList { //sarama.OffsetNewest 获取最新的 //sarama.OffsetOldest 从头读到尾 pc, err := consumer.ConsumePartition("my-topic", int32(partition), sarama.OffsetNewest) if err != nil { fmt.Printf("Failed to start consumer for partition %d: %s\n", partition, err) return } defer pc.AsyncClose() wg.Add(1) go func(pc sarama.PartitionConsumer) { defer wg.Done() for msg := range pc.Messages() { fmt.Printf("Partition:%d, Offset:%d, Key:%s, Value:%s", msg.Partition, msg.Offset, string(msg.Key), string(msg.Value)) fmt.Println() } }(pc) } //time.Sleep(time.Hour) wg.Wait() consumer.Close() } ~~~ > ### 相关阅读 * [kafka学习笔记:知识点整理](https://www.cnblogs.com/cyfonly/p/5954614.html) * [Kafka分区与消费者的关系](https://www.cnblogs.com/cjsblog/p/9664536.html) * [golang kafka小试消息队列](https://www.cnblogs.com/cjsblog/p/9664536.html) * * * * windows gcc not fount 安装 mingw-w64 * [https://sourceforge.net/projects/mingw-w64/](https://sourceforge.net/projects/mingw-w64/)