go語言操做kafka

go語言操做kafka

Kafka是一種高吞吐量的分佈式發佈訂閱消息系統,它能夠處理消費者規模的網站中的全部動做流數據,具備高性能、持久化、多副本備份、橫向擴展等特色。本文介紹瞭如何使用Go語言發送和接收kafka消息。git

sarama

Go語言中鏈接kafka使用第三方庫:github.com/Shopify/saramagithub

下載及安裝

go get github.com/Shopify/sarama

注意事項

sarama v1.20以後的版本加入了zstd壓縮算法,須要用到cgo,在Windows平臺編譯時會提示相似以下錯誤:web

# github.com/DataDog/zstd
exec: "gcc":executable file not found in %PATH%

因此在Windows平臺請使用v1.19版本的sarama。算法

鏈接kafka發送消息

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("this is a test log")
    // 鏈接kafka
    client, err := sarama.NewSyncProducer([]string{"192.168.1.7: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)
}

鏈接kafka消費消息

package main

import (
    "fmt"

    "github.com/Shopify/sarama"
)

// kafka consumer

func main() {
    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("web_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)
    }
}
相關文章
相關標籤/搜索