gateway/external/kafka/kafka.go

47 lines
751 B
Go
Raw Normal View History

2018-04-09 11:37:54 +00:00
package kafka
import (
"context"
"fmt"
"git.loafle.net/commons/logging-go"
"github.com/segmentio/kafka-go"
)
var (
kafkaWriter *kafka.Writer
)
func InitPackage() {
go func() {
kafkaWriter = kafka.NewWriter(kafka.WriterConfig{
Brokers: []string{"192.168.1.50:9092"},
Topic: "overflow-metric-topic",
Balancer: &kafka.LeastBytes{},
})
}()
}
func DestroyPackage() {
go func() {
if err := kafkaWriter.Close(); nil != err {
logging.Logger().Errorf("%v", err)
}
}()
}
func Write(key []byte, value []byte) error {
if nil == kafkaWriter {
return fmt.Errorf("Kafka client is not valid")
}
err := kafkaWriter.WriteMessages(context.Background(),
kafka.Message{
Key: key,
Value: value,
},
)
return err
}