浏览代码

Add an example of using the consumer

Evan Huus 9 年之前
父节点
当前提交
73244fb45a
共有 1 个文件被更改,包括 47 次插入0 次删除
  1. 47 0
      consumer_test.go

+ 47 - 0
consumer_test.go

@@ -1,6 +1,9 @@
 package sarama
 
 import (
+	"log"
+	"os"
+	"os/signal"
 	"sync"
 	"testing"
 	"time"
@@ -842,3 +845,47 @@ func assertMessageOffset(t *testing.T, msg *ConsumerMessage, expectedOffset int6
 		t.Errorf("Incorrect message offset: expected=%d, actual=%d", expectedOffset, msg.Offset)
 	}
 }
+
+// This example shows how to use the consumer to read messages
+// from a single partition.
+func ExampleConsumer() {
+	consumer, err := NewConsumer([]string{"localhost:9092"}, nil)
+	if err != nil {
+		panic(err)
+	}
+
+	defer func() {
+		if err := consumer.Close(); err != nil {
+			log.Fatalln(err)
+		}
+	}()
+
+	partitionConsumer, err := consumer.ConsumePartition("my_topic", 0, OffsetNewest)
+	if err != nil {
+		panic(err)
+	}
+
+	defer func() {
+		if err := partitionConsumer.Close(); err != nil {
+			log.Fatalln(err)
+		}
+	}()
+
+	// Trap SIGINT to trigger a shutdown.
+	signals := make(chan os.Signal, 1)
+	signal.Notify(signals, os.Interrupt)
+
+	consumed := 0
+ConsumerLoop:
+	for {
+		select {
+		case msg := <-partitionConsumer.Messages():
+			log.Printf("Consumed message offset %d\n", msg.Offset)
+			consumed++
+		case <-signals:
+			break ConsumerLoop
+		}
+	}
+
+	log.Printf("Consumed: %d\n", consumed)
+}