github.com/gogf/gkafka@v1.0.1-0.20190702070843-033a14468069/gkafka_test.go (about)

     1  // Copyright 2018 gf Author(https://github.com/gogf/gf). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/gogf/gf.
     6  
     7  package gkafka_test
     8  
     9  import (
    10      "fmt"
    11      "github.com/gogf/gkafka"
    12      "time"
    13  )
    14  
    15  // Create producer.
    16  func Example_producer() {
    17      topic                     := "test"
    18      kafkaConfig               := gkafka.NewConfig()
    19      kafkaConfig.Servers        = "localhost:9092"
    20      kafkaConfig.AutoMarkOffset = false
    21      kafkaConfig.Topics         = topic
    22  
    23      client := gkafka.NewClient(kafkaConfig)
    24      defer client.Close()
    25      for {
    26          s := time.Now().String()
    27          fmt.Println("produce:", s)
    28          if err := client.SyncSend(&gkafka.Message{Value: []byte(s)}); err != nil {
    29              fmt.Println(err)
    30          }
    31          time.Sleep(time.Second)
    32      }
    33  }
    34  
    35  // Create consumer.
    36  func Example_consumer() {
    37      group                     := "test-group"
    38      topic                     := "test"
    39      kafkaConfig               := gkafka.NewConfig()
    40      kafkaConfig.Servers        = "localhost:9092"
    41      kafkaConfig.AutoMarkOffset = false
    42      kafkaConfig.Topics         = topic
    43      kafkaConfig.GroupId        = group
    44  
    45      client := gkafka.NewClient(kafkaConfig)
    46      defer client.Close()
    47  
    48      // Mark the offset from reading.
    49      client.MarkOffset(topic, 0, 6)
    50      for {
    51          if msg, err := client.Receive(); err != nil {
    52              fmt.Println(err)
    53              break
    54          } else {
    55              fmt.Println("consume:", msg.Partition, msg.Offset, string(msg.Value))
    56              msg.MarkOffset()
    57          }
    58      }
    59  }
    60  
    61  // Fetch all topics from server.
    62  func Example_topics() {
    63      config        := gkafka.NewConfig()
    64      config.Servers = "localhost:9092"
    65  
    66      client := gkafka.NewClient(config)
    67      defer client.Close()
    68  
    69      fmt.Println(client.Topics())
    70  }