You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 lines
1.8 KiB

7 years ago
  1. package kafka
  2. import (
  3. "github.com/Shopify/sarama"
  4. "github.com/chrislusf/seaweedfs/weed/glog"
  5. "github.com/chrislusf/seaweedfs/weed/msgqueue"
  6. "github.com/golang/protobuf/proto"
  7. )
  8. func init() {
  9. msgqueue.MessageQueues = append(msgqueue.MessageQueues, &KafkaQueue{})
  10. }
  11. type KafkaQueue struct {
  12. topic string
  13. producer sarama.AsyncProducer
  14. }
  15. func (k *KafkaQueue) GetName() string {
  16. return "kafka"
  17. }
  18. func (k *KafkaQueue) Initialize(configuration msgqueue.Configuration) (err error) {
  19. return k.initialize(
  20. configuration.GetStringSlice("hosts"),
  21. configuration.GetString("topic"),
  22. )
  23. }
  24. func (k *KafkaQueue) initialize(hosts []string, topic string) (err error) {
  25. config := sarama.NewConfig()
  26. config.Producer.RequiredAcks = sarama.WaitForLocal
  27. config.Producer.Partitioner = sarama.NewHashPartitioner
  28. config.Producer.Return.Successes = true
  29. config.Producer.Return.Errors = true
  30. k.producer, err = sarama.NewAsyncProducer(hosts, config)
  31. go k.handleSuccess()
  32. go k.handleError()
  33. return nil
  34. }
  35. func (k *KafkaQueue) SendMessage(key string, message proto.Message) (err error) {
  36. bytes, err := proto.Marshal(message)
  37. if err != nil {
  38. return
  39. }
  40. msg := &sarama.ProducerMessage{
  41. Topic: k.topic,
  42. Key: sarama.StringEncoder(key),
  43. Value: sarama.ByteEncoder(bytes),
  44. }
  45. k.producer.Input() <- msg
  46. return nil
  47. }
  48. func (k *KafkaQueue) handleSuccess() {
  49. for {
  50. pm := <-k.producer.Successes()
  51. if pm != nil {
  52. glog.Infof("producer message success, partition:%d offset:%d key:%v valus:%s", pm.Partition, pm.Offset, pm.Key, pm.Value)
  53. }
  54. }
  55. }
  56. func (k *KafkaQueue) handleError() {
  57. for {
  58. err := <-k.producer.Errors()
  59. if err != nil {
  60. glog.Errorf("producer message error, partition:%d offset:%d key:%v valus:%s error(%v)", err.Msg.Partition, err.Msg.Offset, err.Msg.Key, err.Msg.Value, err.Err)
  61. }
  62. }
  63. }