多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
> ### 十二例 Kafka操作 * 生产者 ~~~ 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 { 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() } ~~~