github.com/OrigamiWang/msd/micro@v0.0.0-20240229032328-b62246268db9/mq/kafka/producer.go (about) 1 package kafka 2 3 import ( 4 "github.com/IBM/sarama" 5 logutil "github.com/OrigamiWang/msd/micro/util/log" 6 ) 7 8 // ProduceMsg produce message 9 // id: 分区键, msg: 消息 10 var ( 11 kafkaProducer sarama.SyncProducer 12 ) 13 14 func init() { 15 var err error 16 17 config := sarama.NewConfig() 18 config.Producer.Return.Successes = true 19 20 kafkaProducer, err = sarama.NewSyncProducer([]string{"localhost:9092"}, config) 21 22 if err != nil { 23 logutil.Error("Failed to start Kafka producer, err: %v", err) 24 } 25 } 26 27 func ProduceMsg(msg *sarama.ProducerMessage) error { 28 partition, offset, err := kafkaProducer.SendMessage(msg) 29 if err != nil { 30 logutil.Error("Failed to send message, err: %v", err) 31 return err 32 } 33 34 logutil.Info("Message is stored in topic(%s)/partition(%d)/offset(%d)\n", msg.Topic, partition, offset) 35 return nil 36 }