12.golang操作kafka
# 01.基本使用
- 安装
go get github.com/Shopify/sarama
go mod tidy
1
2
2
# 1.1 生产者
package main
import (
"fmt"
"github.com/Shopify/sarama"
)
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)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# 1.2 消费者
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()
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
上次更新: 2024/4/1 16:53:26