【kafka】go操作kafka

462 阅读4分钟

0/参考网址

blog.csdn.net/ydl1128/art…

总结

Sarama是一个用于与Apache Kafka通信的Go语言客户端库。
在Sarama库中,NewClient方法用于创建一个新的Kafka客户端实例。
该方法需要提供一些配置选项,以便与Kafka服务建立连接并进行通信。

先创建与kafka服务进行通信的客户端实例client,然后根据客户端实例去创建生产者或者消费者。

1/sarama介绍

截止当前时间,github上golang语言操作kafka的库包主要有两个:
  <1> Shopify/sarama starts   (github.com/Shopify/sarama)
         saram 使用纯go语言编写
  <2> confluentinc/confluent-kafka-go starts
         confluent-kafka-go 这是包装了c的api

2/在go语言操作kafka开发中,如果使用开源的sarama库包

<1>下载及安装
    go get github.com/Shopify/sarama  
    
<2>注意事项
sarama v1.20之后的版本加入了zstd压缩算法,需要用到cgo,在Windows平台编译时会提示类似如下错误:
    github.com/DataDog/zstd
    exec: "gcc":executable file not found in %PATH%

所以在Windows平台请使用v1.19版本的sarama。

3/发送消息

只有生产者(producer)才会发送消息到kafak-topic,topic主题,是对消息的分类。
所以,这里是构建生产者producer的客户端,来发送消息msg到topic
package main

import (
    "fmt"
    "github.com/Shopify/sarama"
)

// 基于sarama第三方库开发的kafka client

func main() {
    // 初始化一个配置文件对象,这是一个空的配置文件
    config := sarama.NewConfig()
       
    // 该配置哪些参数,接下来可以一一去配置
    // 发送完数据需要leader和follow都确认
    config.Producer.RequiredAcks = sarama.WaitForAll    
    
    // 新选出一个partition
    config.Producer.Partitioner = sarama.NewRandomPartitioner 
    
    // 成功交付的消息将在success channel返回
    config.Producer.Return.Successes = true                   
    
    // 第一步:连接kafka服务器,构建一个生产者的客户端producer_client
    // Sync代表是同步的,也就是说只能发完一条msg,再发送另一条msg。async是异步发送消息。
    // NewSyncProducer()函数,入参是2个,第一个是ip:port,及kafka的服务地址,第二个是配置文件
    producer_client, err := sarama.NewSyncProducer([]string{"192.168.1.7:9092"}, 
                                                   config)
    if err != nil {
        fmt.Println("producer closed, err:", err)
        return
    }
    defer client.Close() // 执行完该main函数以后,最后要关闭客户端。
    
    // 第二步:构造一个消息
    msg := &sarama.ProducerMessage{} 
    msg.Topic = "web_log" // 要写入的topic的名字
    msg.Value = sarama.StringEncoder("this is a test log")
    
    // 第三步:发送消息
    // 用上面构建的生产者的客户端,来发送消息到topic
    // 发送消息有很多方式,这里是同步发送
    pid, offset, err := producer_client.SendMessage(msg) 
    if err != nil {
        fmt.Println("send msg failed, err:", err)
        return
    }
    // 发送完消息之后,会得到pid, offset等返回值
    fmt.Printf("pid:%v offset:%v\n", pid, offset)
}

4/订阅消费消息

消费者是从topic中接收消息,然后消费的。
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
    }

    // 根据topic取到所有的分区,并且打印所有的分区
    partitionList, err := consumer.Partitions("web_log")
    if err != nil {
        fmt.Printf("fail to get list of partition:err%v\n", err)
        return
    }
    fmt.Println(partitionList)

    // 遍历所有的分区
    for partition := range partitionList {
        // 针对每个分区创建一个对应的分区消费者
        partition_consumer, 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 partition_consumer.AsyncClose()

        // 异步从每个分区消费信息
        go func(sarama.PartitionConsumer) {
            for msg := range partition_consumer.Messages() {
                fmt.Printf("Partition:%d Offset:%d Key:%v Value:%v", msg.Partition, msg.Offset, msg.Key, msg.Value)

        }

        }(partition_consumer)

    }

}

5/配置文件

在,我们编辑 my.ini 文件并输入以下内容(*部分内容来自 Grafana*)。  
# possible values : production, development
app_mode = development

[paths]
# Path to where grafana can store temp files, sessions, and the sqlite3 db (if that is used)
data = /home/git/grafana

[server]
# Protocol (http or https)
protocol = http

# The http port  to use
http_port = 9999

# Redirect to correct domain if host header does not match domain
# Prevents DNS rebinding attacks
enforce_domain = true

6/编写main.go文件

package main

import (
    "fmt"
    "os"
    "gopkg.in/ini.v1"
)

func main() {
    // 加载配置文件
    cfg, err := ini.Load("my.ini")
    if err != nil {
        fmt.Printf("Fail to read file: %v", err)
        os.Exit(1)
    }

    // 典型读取操作,默认分区可以使用空字符串表示
    fmt.Println("App Mode:", cfg.Section("").Key("app_mode").String())
    fmt.Println("Data Path:", cfg.Section("paths").Key("data").String())

    // 我们可以做一些候选值限制的操作
    fmt.Println("Server Protocol:",
        cfg.Section("server").Key("protocol").In("http", []string{"http", "https"}))
    // 如果读取的值不在候选列表内,则会回退使用提供的默认值
    fmt.Println("Email Protocol:",
        cfg.Section("server").Key("protocol").In("smtp", []string{"imap", "smtp"}))

    // 试一试自动类型转换
    fmt.Printf("Port Number: (%[1]T) %[1]d\n", cfg.Section("server").Key("http_port").MustInt(9999))
    fmt.Printf("Enforce Domain: (%[1]T) %[1]v\n", cfg.Section("server").Key("enforce_domain").MustBool(false))
    
    // 差不多了,修改某个值然后进行保存
    cfg.Section("").Key("app_mode").SetValue("production")
    cfg.SaveTo("my.ini.local")
}
结果如下所示:
$ go run main.go

    App Mode: development
    Data Path: /home/git/grafana
    Server Protocol: http
    Email Protocol: smtp
    Port Number: (int) 9999
    Enforce Domain: (bool) true

// 看下配置文件中的内容
$ cat my.ini.local
# possible values : production, development
app_mode = production

[paths]
# Path to where grafana can store temp files, sessions, and the sqlite3 db (if that is used)
data = /home/git/grafana
...