git.zd.zone/hrpc/hrpc@v0.0.12/mq/kafka/kafka.go (about) 1 package kafka 2 3 import ( 4 "encoding/json" 5 "log" 6 "os" 7 "strings" 8 9 "git.zd.zone/hrpc/hrpc/utils/uniqueid" 10 "github.com/Shopify/sarama" 11 ) 12 13 type Kafka struct { 14 client sarama.Client 15 opt *Options 16 } 17 18 var k *Kafka 19 20 func New(opts ...Option) *Kafka { 21 if k != nil { 22 k.Destory() 23 } 24 k = &Kafka{ 25 opt: mergeOptions(opts...), 26 } 27 sarama.Logger = log.New(os.Stdout, "[sarama]", log.LstdFlags) 28 return k 29 } 30 31 func (k *Kafka) Name() string { 32 return "kafka" 33 } 34 35 // Load can load a set of configurations represented by a JSON string 36 // However, it is invalid if someone provides options at the contruction function 37 // Because the configurations provided at the New() function have the highest priority 38 func (k *Kafka) Load(src []byte) error { 39 if k.opt.Brokers != "" { 40 return nil 41 } 42 return json.Unmarshal(src, k.opt) 43 } 44 45 func (k *Kafka) Connect() error { 46 config := sarama.NewConfig() 47 config.ClientID = uniqueid.IP() 48 config.Version = k.opt.version 49 config.Producer.RequiredAcks = sarama.RequiredAcks(k.opt.Acks) 50 config.Producer.Return.Successes = true 51 config.Consumer.Offsets.AutoCommit.Enable = k.opt.AutoCommit 52 config.Consumer.Offsets.Initial = k.opt.OffsetInitial 53 if k.opt.SASL.enabled || k.opt.SASL.Username != "" { 54 config.Net.SASL.Enable = true 55 config.Net.SASL.User = k.opt.SASL.Username 56 config.Net.SASL.Password = k.opt.SASL.Password 57 config.Net.SASL.Mechanism = sarama.SASLTypePlaintext 58 } 59 60 c, err := sarama.NewClient(strings.Split(k.opt.Brokers, ","), config) 61 if err != nil { 62 return err 63 } 64 k.client = c 65 return nil 66 } 67 68 func (k *Kafka) Destory() { 69 if k.client != nil { 70 k.client.Close() 71 } 72 return 73 } 74 75 func Client() sarama.Client { 76 return k.client 77 }