1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
|
[](https://github.com/optiopay/kafka/actions?query=workflow%3AKafka)
[](https://godoc.org/github.com/optiopay/kafka/v2)
# Kafka
Kafka is Go client library for [Apache Kafka](https://kafka.apache.org/)
server, released under [MIT license](LICENSE]).
Kafka provides minimal abstraction over wire protocol, support for transparent
failover and easy to use blocking API.
* [godoc](https://godoc.org/github.com/optiopay/kafka/v2) generated documentation,
* [code examples](https://godoc.org/github.com/optiopay/kafka/v2#pkg-examples)
## Example
Write all messages from stdin to kafka and print all messages from kafka topic
to stdout.
```go
package main
import (
"bufio"
"log"
"os"
"strings"
"github.com/optiopay/kafka/v2"
"github.com/optiopay/kafka/v2/proto"
)
const (
topic = "my-messages"
partition = 0
)
var kafkaAddrs = []string{"localhost:9092", "localhost:9093"}
// printConsumed read messages from kafka and print them out
func printConsumed(broker kafka.Client) {
conf := kafka.NewConsumerConf(topic, partition)
conf.StartOffset = kafka.StartOffsetNewest
consumer, err := broker.Consumer(conf)
if err != nil {
log.Fatalf("cannot create kafka consumer for %s:%d: %s", topic, partition, err)
}
for {
msg, err := consumer.Consume()
if err != nil {
if err != kafka.ErrNoData {
log.Printf("cannot consume %q topic message: %s", topic, err)
}
break
}
log.Printf("message %d: %s", msg.Offset, msg.Value)
}
log.Print("consumer quit")
}
// produceStdin read stdin and send every non empty line as message
func produceStdin(broker kafka.Client) {
producer := broker.Producer(kafka.NewProducerConf())
input := bufio.NewReader(os.Stdin)
for {
line, err := input.ReadString('\n')
if err != nil {
log.Fatalf("input error: %s", err)
}
line = strings.TrimSpace(line)
if line == "" {
continue
}
msg := &proto.Message{Value: []byte(line)}
if _, err := producer.Produce(topic, partition, msg); err != nil {
log.Fatalf("cannot produce message to %s:%d: %s", topic, partition, err)
}
}
}
func main() {
conf := kafka.NewBrokerConf("test-client")
conf.AllowTopicCreation = true
// connect to kafka cluster
broker, err := kafka.Dial(kafkaAddrs, conf)
if err != nil {
log.Fatalf("cannot connect to kafka cluster: %s", err)
}
defer broker.Close()
go printConsumed(broker)
produceStdin(broker)
}
```
|