git.zd.zone/hrpc/hrpc@v0.0.12/mq/kafka/README.md (about) 1 # Introduction 2 3 ## Usage 4 5 **For Initialization:** 6 ``` 7 import ( 8 // ... 9 "github.com/hirpc/hrpc/mq/kafka" 10 "github.com/hirpc/hrpc/log" 11 "github.com/hirpc/hrpc/option" 12 ) 13 14 func main() { 15 s, err := hrpc.NewServer( 16 option.WithMessageQueues(kafka.New(kafka.WithVersion("1.1.1"))), 17 ) 18 if err != nil { 19 panic(err) 20 } 21 // .... 22 } 23 ``` 24 25 **For Producer:** 26 ``` 27 import ( 28 "github.com/hirpc/hrpc/log" 29 "github.com/hirpc/hrpc/mq/kafka" 30 ) 31 32 func Foo() error { 33 if err := kafka.Produce( 34 "TOPIC_NAME", 35 *kafka.NewProduceMessage([]byte("MESSAGE")), 36 ); err != nil { 37 log.WithFields(ctx).Error(err) 38 return err 39 } 40 return nil 41 } 42 43 ``` 44 45 **For Consumer:** 46 ``` 47 import ( 48 // ... 49 "github.com/hirpc/hrpc/mq/kafka" 50 "github.com/hirpc/hrpc/log" 51 "github.com/hirpc/hrpc/option" 52 ) 53 54 type tmp struct{} 55 56 // Handle will receive messages from the kafka with topic, key, value, partition, offset/ 57 // Every message received should return nil or error. The difference between these two values is: 58 // nil -> do commit for this message 59 // error -> do NOT commit for this message 60 func (t tmp) Handle(ctx context.Context, topic string, key, value []byte, partition int32, offset int64) error { 61 log.WithFields(ctx, "KKK", "Kafka").Warn(topic, string(value), partition, offset) 62 return nil 63 } 64 65 func main() { 66 s, err := hrpc.NewServer( 67 // ... 68 option.WithMessageQueues(kafka.New(kafka.WithVersion("1.1.1"))), 69 // ... 70 option.WithHealthCheck(), 71 ) 72 if err != nil { 73 panic(err) 74 } 75 76 kafka.RegisterGroupConsumer(hrpc.BackgroundContext(), tmp{}, "GROUP_NAME", "TOPIC_NAME") 77 78 if err := s.Serve(); err != nil { 79 panic(err) 80 } 81 } 82 ```