kafka-console-topicconsumer.go 3.0 KB

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