1. 程式人生 > >golang基礎-WaitGroup、kafka消費者

golang基礎-WaitGroup、kafka消費者

nginx done star produce name message time 分區 鏈接

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)
}
  • 然後最後看效果圖如下:

golang基礎-WaitGroup、kafka消費者