golang基础-WaitGroup、kafka消费者
kafka消费者
以下博客是通过生产者创建、发送消息至kafka
博客链接
现在我们站在消费者的角度,来进行收取消息
package main
import (
"fmt"
"strings"
"sync"
"github.com/Shopify/sarama"
)
var (
wg sync.WaitGroup
)
func main() {
//创建消费者
consumer, err := sarama.NewConsumer(strings.Split("192.168.11.48:9092", ","), nil)
if err != nil {
fmt.Println("Failed to start consumer: %s", err)
return
}
//设置分区
partitionList, err := consumer.Partitions("nginx_log")
if err != nil {
fmt.Println("Failed to get the list of partitions: ", err)
return
}
fmt.Println(partitionList)
//循环分区
for partition := range partitionList {
pc, err := consumer.ConsumePartition("nginx_log", int32(partition), sarama.OffsetNewest)
if err != nil {
fmt.Printf("Failed to start consumer for partition %d: %s\n", partition, err)
return
}
defer pc.AsyncClose()
go func(pc sarama.PartitionConsumer) {
wg.Add(1)
for msg := range pc.Messages() {
fmt.Printf("Partition:%d, Offset:%d, Key:%s, Value:%s", msg.Partition, msg.Offset, string(msg.Key), string(msg.Value))
fmt.Println()
}
wg.Done()
}(pc)
}
//time.Sleep(time.Hour)
wg.Wait()
consumer.Close()
}
接下来我们测试上面的消费者示例代码,在进行测试前我们需要如下的准备工作
1、启动zookeeper
2、启动kafka
3、创立生产者topic
.\bin\windows\kafka-topics.bat --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic linlin
4、执行生产者发送消息至kafka代码
5、执行消费者代码程序
第4步的代码如下:
package main
import (
"fmt"
"github.com/Shopify/sarama"
)
func main() {
config := sarama.NewConfig()
config.Producer.RequiredAcks = sarama.WaitForAll
config.Producer.Partitioner = sarama.NewRandomPartitioner
config.Producer.Return.Successes = true
msg := &sarama.ProducerMessage{}
msg.Topic = "nginx_log"
msg.Value = sarama.StringEncoder("this is a good test, my message is good")
client, err := sarama.NewSyncProducer([]string{"192.168.11.28:9092"}, config)
if err != nil {
fmt.Println("producer close, err:", err)
return
}
defer client.Close()
pid, offset, err := client.SendMessage(msg)
if err != nil {
fmt.Println("send message failed,", err)
return
}
fmt.Printf("pid:%v offset:%v\n", pid, offset)
}
- 然后最后看效果图如下: