kafka-console-consumer.go 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "log"
  6. "os"
  7. "os/signal"
  8. "strconv"
  9. "strings"
  10. "sync"
  11. "github.com/Shopify/sarama"
  12. )
  13. var (
  14. brokerList = flag.String("brokers", os.Getenv("KAFKA_PEERS"), "The comma separated list of brokers in the Kafka cluster")
  15. topic = flag.String("topic", "", "REQUIRED: the topic to consume")
  16. partitions = flag.String("partitions", "all", "The partitions to consume, can be 'all' or comma-separated numbers")
  17. offset = flag.String("offset", "newest", "The offset to start with. Can be `oldest`, `newest`")
  18. verbose = flag.Bool("verbose", false, "Whether to turn on sarama logging")
  19. bufferSize = flag.Int("buffer-size", 256, "The buffer size of the message channel.")
  20. logger = log.New(os.Stderr, "", log.LstdFlags)
  21. )
  22. func main() {
  23. flag.Parse()
  24. if *brokerList == "" {
  25. printUsageErrorAndExit("You have to provide -brokers as a comma-separated list, or set the KAFKA_PEERS environment variable.")
  26. }
  27. if *topic == "" {
  28. printUsageErrorAndExit("-topic is required")
  29. }
  30. if *verbose {
  31. sarama.Logger = logger
  32. }
  33. var initialOffset int64
  34. switch *offset {
  35. case "oldest":
  36. initialOffset = sarama.OffsetOldest
  37. case "newest":
  38. initialOffset = sarama.OffsetNewest
  39. default:
  40. printUsageErrorAndExit("-offset should be `oldest` or `newest`")
  41. }
  42. c, err := sarama.NewConsumer(strings.Split(*brokerList, ","), nil)
  43. if err != nil {
  44. printErrorAndExit(69, "Failed to start consumer: %s", err)
  45. }
  46. partitionList, err := getPartitions(c)
  47. if err != nil {
  48. printErrorAndExit(69, "Failed to get the list of partitions: %s", err)
  49. }
  50. var (
  51. messages = make(chan *sarama.ConsumerMessage, *bufferSize)
  52. closing = make(chan struct{})
  53. wg sync.WaitGroup
  54. )
  55. go func() {
  56. signals := make(chan os.Signal, 1)
  57. signal.Notify(signals, os.Kill, os.Interrupt)
  58. <-signals
  59. logger.Println("Initiating shutdown of consumer...")
  60. close(closing)
  61. }()
  62. for _, partition := range partitionList {
  63. pc, err := c.ConsumePartition(*topic, partition, initialOffset)
  64. if err != nil {
  65. printErrorAndExit(69, "Failed to start consumer for partition %d: %s", partition, err)
  66. }
  67. go func(pc sarama.PartitionConsumer) {
  68. <-closing
  69. pc.AsyncClose()
  70. }(pc)
  71. wg.Add(1)
  72. go func(pc sarama.PartitionConsumer) {
  73. defer wg.Done()
  74. for message := range pc.Messages() {
  75. messages <- message
  76. }
  77. }(pc)
  78. }
  79. go func() {
  80. for msg := range messages {
  81. fmt.Printf("Partition:\t%d\n", msg.Partition)
  82. fmt.Printf("Offset:\t%d\n", msg.Offset)
  83. fmt.Printf("Key:\t%s\n", string(msg.Key))
  84. fmt.Printf("Value:\t%s\n", string(msg.Value))
  85. fmt.Println()
  86. }
  87. }()
  88. wg.Wait()
  89. logger.Println("Done consuming topic", *topic)
  90. close(messages)
  91. if err := c.Close(); err != nil {
  92. logger.Println("Failed to close consumer: ", err)
  93. }
  94. }
  95. func getPartitions(c sarama.Consumer) ([]int32, error) {
  96. if *partitions == "all" {
  97. return c.Partitions(*topic)
  98. }
  99. tmp := strings.Split(*partitions, ",")
  100. var pList []int32
  101. for i := range tmp {
  102. val, err := strconv.ParseInt(tmp[i], 10, 32)
  103. if err != nil {
  104. return nil, err
  105. }
  106. pList = append(pList, int32(val))
  107. }
  108. return pList, nil
  109. }
  110. func printErrorAndExit(code int, format string, values ...interface{}) {
  111. fmt.Fprintf(os.Stderr, "ERROR: %s\n", fmt.Sprintf(format, values...))
  112. fmt.Fprintln(os.Stderr)
  113. os.Exit(code)
  114. }
  115. func printUsageErrorAndExit(format string, values ...interface{}) {
  116. fmt.Fprintf(os.Stderr, "ERROR: %s\n", fmt.Sprintf(format, values...))
  117. fmt.Fprintln(os.Stderr)
  118. fmt.Fprintln(os.Stderr, "Available command line options:")
  119. flag.PrintDefaults()
  120. os.Exit(64)
  121. }