Go操作Kafka

470 次浏览次阅读
没有评论

sarama

Go 语言中连接 kafka 使用第三方库: github.com/Shopify/sarama。

生产者


func sendMsg() {config := sarama.NewConfig()
    config.Producer.RequiredAcks = sarama.WaitForAll
    config.Producer.Partitioner = sarama.NewRandomPartitioner
    config.Producer.Return.Successes = true

    msg := &sarama.ProducerMessage{
        Topic: "test_log",
        Value: sarama.StringEncoder("this is a test log"),
    }
    client, err := sarama.NewSyncProducer([]string{"127.0.0.1:9092"}, config)
    if err != nil {fmt.Println("send msg failed, 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)
}

消费者

func consumerMsg() {consumer, err := sarama.NewConsumer([]string{"127.0.0.1:9092"}, nil)
    if err != nil {fmt.Printf("fail to start consumer, err:%v\n", err)
        return
    }
    partitionList, err := consumer.Partitions("web_log") // 根据 topic 取到所有的分区
    if err != nil {fmt.Printf("fail to get list of partition:err%v\n", err)
        return
    }
    fmt.Println(partitionList)
    for partition := range partitionList { // 遍历所有的分区
        // 针对每个分区创建一个对应的分区消费者
        pc, err := consumer.ConsumePartition("test_log", int32(partition), sarama.OffsetNewest)
        if err != nil {fmt.Printf("failed to start consumer for partition %d,err:%v\n", partition, err)
            return
        }
        defer pc.AsyncClose()
        // 异步从每个分区消费信息
        go func(sarama.PartitionConsumer) {for msg := range pc.Messages() {fmt.Printf("Partition:%d Offset:%d Key:%v Value:%v", msg.Partition, msg.Offset, msg.Key, msg.Value)
            }
        }(pc)
    }
}
正文完
 0
评论(没有评论)