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.

76 lines
1.8 KiB

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