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

1.安装

go get github.com/Shopify/sarama

ps:saramav1.20之后的版本加入了facebook的压缩算法zstd,需要用到cgo,在windows平台编译时会报错:

exec:"gcc":executable file not found in %PATH%

所以只能下载v1.19版本

require github.com/Shopify/sarama v1.28.0 // indirect

修改为

require github.com/Shopify/sarama v1.19

执行命令

go mod download
go mod tidy
go mod tidy -v

2.编码

2.1 生产者

package main

import (
	"fmt"
	"sync"

	"github.com/Shopify/sarama"
)

var wg sync.WaitGroup

func main() {
	config := sarama.NewConfig()
	//设置
	//ack应答机制
	config.Producer.RequiredAcks = sarama.WaitForAll

	//发送分区
	config.Producer.Partitioner = sarama.NewRandomPartitioner

	//回复确认
	config.Producer.Return.Successes = true

	//构造一个消息
	msg := &sarama.ProducerMessage{}
	msg.Topic = "weatherStation"
	msg.Value = sarama.StringEncoder("test:weatherStation device")

	//连接kafka
	client, err := sarama.NewSyncProducer([]string{"192.168.31.204:9092"}, config)
	if err != nil {
		fmt.Println("producer closed,err:", err)
	}
	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)

}

2.2 查看文件

cd /tmp/kafka-logs/

#可以看到weather-0的文件夹,上面的topic就是weatherStation
ls -l

#查看文件夹
ls weatherStation-0/ -l

image-20210505032606517

没错,partition在服务器上的表现形式就是一个一个的文件夹,每个partition的文件夹下面会有多组segment文件,每组segment文件又包含.index文件、.log文件、.timeindex文件是哪个文件,其中.log文件就是实际存储message的地方,而.index.timeindex文件为索引文件,用于检索消息。

2.3 尝试用命令消费

./kafka-console-consumer.sh --bootstrap-server 127.0.0.1:9092 --topic weatherStation --from-beginning

image-20210505032812586

2.4 消费者

package main

import (
	"fmt"
	"sync"

	"github.com/Shopify/sarama"
)

var wg sync.WaitGroup

func main() {
	//创建新的消费者
	consumer, err := sarama.NewConsumer([]string{"192.168.31.204:9092"}, nil)
	if err != nil {
		fmt.Println("fail to start consumer", err)
	}
	//根据topic获取所有的分区列表
	partitionList, err := consumer.Partitions("weatherStation")
	if err != nil {
		fmt.Println("fail to get list of partition,err:", err)
	}
	fmt.Println(partitionList)
	//遍历所有的分区
	for p := range partitionList {
		//针对每一个分区创建一个对应分区的消费者
		pc, err := consumer.ConsumePartition("weatherStation", int32(p), sarama.OffsetNewest)
		if err != nil {
			fmt.Printf("failed to start consumer for partition %d,err:%v\n", p, err)
		}
		defer pc.AsyncClose()
		wg.Add(1)
		//异步从每个分区消费信息
		go func(sarama.PartitionConsumer) {
			for msg := range pc.Messages() {
				fmt.Printf("partition:%d Offse:%d Key:%v Value:%s \n",
					msg.Partition, msg.Offset, msg.Key, msg.Value)
			}
		}(pc)
	}
	wg.Wait()
}
  • 用上面的生产者生产消息,用下面的消费者消费
go build -o kafkaProducer.exe
.\kafkaProducer.exe


go build -o kafkaConsumer.exe
.\kafkaConsumer.exe

image-20210505033208317