本文内容纲要:

生产者:

package main

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

func main() {
    config := sarama.NewConfig()
    config.Producer.RequiredAcks = sarama.WaitForAll
    config.Producer.Partitioner = sarama.NewRandomPartitioner
    config.Producer.Return.Successes = true

    client, err := sarama.NewSyncProducer([]string{"localhost:9092"}, config)
    if err != nil {
        fmt.Println("producer close, err:", err)
        return
    }

    defer client.Close()

    for true {
        msg := &sarama.ProducerMessage{}
        msg.Topic = "nginx_log"
        msg.Value = sarama.StringEncoder("this is s good test")
        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)
        time.Sleep(10*time.Second)
    }
}

消费者

package main

import (
    "sync"
    "github.com/Shopify/sarama"
    "strings"
    "fmt"
    "time"
)

var wg sync.WaitGroup //用来等待一组goroutine结束 

func main() {
    consumer, err := sarama.NewConsumer(strings.Split("localhost:9092", ","), nil)
    if err != nil {
        fmt.Println("failed to start consumer:%s", err)
        return
    }
    partitionList, err := consumer.Partitions("nginx_long")
    if err != nil {
        fmt.Println("failed to get the list of partitions:", err)
    }
    fmt.Println(partitionList)
    for partition := range partitionList{
        pc, err := consumer.ConsumePartition("nginx_log", int32(partition),sarama.OffsetNewest)
        if err != nil {
            fmt.Println("failed to start consumer for partition %d:%s\n", partition, err)
            return
        }
        defer pc.AsyncClose()
        go func(sarama.PartitionConsumer) { //kafka里有几个分区就起几个goroutine
            for msg := range pc.Messages(){//返回一个channel
                fmt.Printf("Partition:%d, Offset:%d, key:%s, value:%s", msg.Partition, msg.Offset, string(msg.Key), string(msg.Value))
                fmt.Println()
            }
        }(pc)
    }

    time.Sleep(time.Hour)
    consumer.Close()
}

生产者执行结果界面

Image

消费者执行结果界面

Image

本文内容总结: