package main
import (
"context"
"fmt"
"log"
"time"
"github.com/Shopify/sarama"
)
const (
TOPIC = "lotsof"
KAFKA1 = "localhost:9092"
KAFKA2 = "localhost:9093"
)
func main() {
异步生产者()
}
type 消费组Handler struct {
}
func (消费组Handler) Setup(sarama.ConsumerGroupSession) error { return nil }
func (消费组Handler) Cleanup(sarama.ConsumerGroupSession) error { return nil }
func (消费组Handler) ConsumeClaim(session sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error {
for msg := range claim.Messages() {
log.Printf("Message claimed: value = %s, timestamp = %v, topic = %s", msg.Value, msg.Timestamp, msg.Topic)
session.MarkMessage(msg, "")
}
return nil
}
func 消费组() {
config := sarama.NewConfig()
config.Consumer.Return.Errors = false
config.Version = sarama.V0_10_2_0
config.Consumer.Offsets.Initial = sarama.OffsetOldest
group, err := sarama.NewConsumerGroup([]string{KAFKA1, KAFKA2}, "my-group", config)
if err != nil {
panic(err)
}
defer group.Close()
fmt.Println("Consumed start")
ctx := context.Background()
for {
topics := []string{TOPIC}
handler := 消费组Handler{}
err := group.Consume(ctx, topics, handler)
if err != nil {
panic(err)
}
}
}
func 同步生产者() {
producer, err := sarama.NewSyncProducer([]string{KAFKA1, KAFKA2}, nil)
if err != nil {
log.Fatalln(err)
}
defer producer.Close()
msg := &sarama.ProducerMessage{
Topic: TOPIC,
Value: sarama.StringEncoder("testing 123"),
}
partition, offset, err := producer.SendMessage(msg)
if err != nil {
log.Printf("FAILED to send message: %s\n", err)
} else {
log.Printf("> 消息发送成功:message sent to partition %d at offset %d\n", partition, offset)
}
}
func 异步生产者() {
config := sarama.NewConfig()
config.Producer.Return.Successes = true
config.Producer.Return.Errors = true
producer, err := sarama.NewAsyncProducer([]string{KAFKA1, KAFKA2}, config)
if err != nil {
panic(err)
}
message := &sarama.ProducerMessage{Topic: TOPIC, Value: sarama.StringEncoder("message is 123321")}
producer.Input() <- message
time.Sleep(2 * time.Second)
select {
case res := <-producer.Successes():
fmt.Printf("%T---%+v\n", res, res)
case err := <-producer.Errors():
fmt.Printf("%T---%+v\n", err, err)
}
}
- 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
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109