producer.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. package sarama
  2. // ProducerConfig is used to pass multiple configuration options to NewProducer.
  3. type ProducerConfig struct {
  4. Partitioner Partitioner // Chooses the partition to send messages to, or randomly if this is nil.
  5. RequiredAcks RequiredAcks // The level of acknowledgement reliability needed from the broker (defaults to no acknowledgement).
  6. Timeout int32 // The maximum time in ms the broker will wait the receipt of the number of RequiredAcks.
  7. Compression CompressionCodec // The type of compression to use on messages (defaults to no compression).
  8. }
  9. // Producer publishes Kafka messages on a given topic. It routes messages to the correct broker, refreshing metadata as appropriate,
  10. // and parses responses for errors. You must call Close() on a producer to avoid leaks, it may not be garbage-collected automatically when
  11. // it passes out of scope (this is in addition to calling Close on the underlying client, which is still necessary).
  12. type Producer struct {
  13. client *Client
  14. topic string
  15. config ProducerConfig
  16. }
  17. // NewProducer creates a new Producer using the given client. The resulting producer will publish messages on the given topic.
  18. func NewProducer(client *Client, topic string, config *ProducerConfig) (*Producer, error) {
  19. if config == nil {
  20. config = new(ProducerConfig)
  21. }
  22. if config.RequiredAcks < -1 {
  23. return nil, ConfigurationError("Invalid RequiredAcks")
  24. }
  25. if config.Timeout < 0 {
  26. return nil, ConfigurationError("Invalid Timeout")
  27. }
  28. if config.Partitioner == nil {
  29. config.Partitioner = NewRandomPartitioner()
  30. }
  31. if topic == "" {
  32. return nil, ConfigurationError("Empty topic")
  33. }
  34. p := new(Producer)
  35. p.client = client
  36. p.topic = topic
  37. p.config = *config
  38. return p, nil
  39. }
  40. // Close shuts down the producer and flushes any messages it may have buffered. You must call this function before
  41. // a producer object passes out of scope, as it may otherwise leak memory. You must call this before calling Close
  42. // on the underlying client.
  43. func (p *Producer) Close() error {
  44. // no-op for now, adding for consistency and so the API doesn't change when we add buffering
  45. // (which will require a goroutine, which will require a close method in order to flush the buffer).
  46. return nil
  47. }
  48. // SendMessage sends a message with the given key and value. The partition to send to is selected by the Producer's Partitioner.
  49. // To send strings as either key or value, see the StringEncoder type.
  50. func (p *Producer) SendMessage(key, value Encoder) error {
  51. return p.safeSendMessage(key, value, true)
  52. }
  53. func (p *Producer) choosePartition(key Encoder) (int32, error) {
  54. partitions, err := p.client.Partitions(p.topic)
  55. if err != nil {
  56. return -1, err
  57. }
  58. numPartitions := int32(len(partitions))
  59. choice := p.config.Partitioner.Partition(key, numPartitions)
  60. if choice < 0 || choice >= numPartitions {
  61. return -1, InvalidPartition
  62. }
  63. return partitions[choice], nil
  64. }
  65. func (p *Producer) safeSendMessage(key, value Encoder, retry bool) error {
  66. partition, err := p.choosePartition(key)
  67. if err != nil {
  68. return err
  69. }
  70. var keyBytes []byte
  71. var valBytes []byte
  72. if key != nil {
  73. keyBytes, err = key.Encode()
  74. if err != nil {
  75. return err
  76. }
  77. }
  78. valBytes, err = value.Encode()
  79. if err != nil {
  80. return err
  81. }
  82. broker, err := p.client.Leader(p.topic, partition)
  83. if err != nil {
  84. return err
  85. }
  86. if p.config.Compression != CompressionNone {
  87. set := new(MessageSet)
  88. set.addMessage(&Message{Codec: CompressionNone, Key: keyBytes, Value: valBytes})
  89. valBytes, err = encode(set)
  90. if err != nil {
  91. return err
  92. }
  93. }
  94. request := &ProduceRequest{RequiredAcks: p.config.RequiredAcks, Timeout: p.config.Timeout}
  95. request.AddMessage(p.topic, partition, &Message{Codec: p.config.Compression, Key: keyBytes, Value: valBytes})
  96. response, err := broker.Produce(p.client.id, request)
  97. switch err {
  98. case nil:
  99. break
  100. case EncodingError:
  101. return err
  102. default:
  103. if !retry {
  104. return err
  105. }
  106. p.client.disconnectBroker(broker)
  107. return p.safeSendMessage(key, value, false)
  108. }
  109. if response == nil {
  110. return nil
  111. }
  112. block := response.GetBlock(p.topic, partition)
  113. if block == nil {
  114. return IncompleteResponse
  115. }
  116. switch block.Err {
  117. case NoError:
  118. return nil
  119. case UnknownTopicOrPartition, NotLeaderForPartition, LeaderNotAvailable:
  120. if !retry {
  121. return block.Err
  122. }
  123. err = p.client.RefreshTopicMetadata(p.topic)
  124. if err != nil {
  125. return err
  126. }
  127. return p.safeSendMessage(key, value, false)
  128. }
  129. return block.Err
  130. }