producer.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  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. p := new(Producer)
  32. p.client = client
  33. p.topic = topic
  34. p.config = *config
  35. return p, nil
  36. }
  37. // Close shuts down the producer and flushes any messages it may have buffered. You must call this function before
  38. // a producer object passes out of scope, as it may otherwise leak memory. You must call this before calling Close
  39. // on the underlying client.
  40. func (p *Producer) Close() error {
  41. // no-op for now, adding for consistency and so the API doesn't change when we add buffering
  42. // (which will require a goroutine, which will require a close method in order to flush the buffer).
  43. return nil
  44. }
  45. // SendMessage sends a message with the given key and value. The partition to send to is selected by the Producer's Partitioner.
  46. // To send strings as either key or value, see the StringEncoder type.
  47. func (p *Producer) SendMessage(key, value Encoder) error {
  48. return p.safeSendMessage(key, value, true)
  49. }
  50. func (p *Producer) choosePartition(key Encoder) (int32, error) {
  51. partitions, err := p.client.Partitions(p.topic)
  52. if err != nil {
  53. return -1, err
  54. }
  55. numPartitions := int32(len(partitions))
  56. choice := p.config.Partitioner.Partition(key, numPartitions)
  57. if choice < 0 || choice >= numPartitions {
  58. return -1, InvalidPartition
  59. }
  60. return partitions[choice], nil
  61. }
  62. func (p *Producer) safeSendMessage(key, value Encoder, retry bool) error {
  63. partition, err := p.choosePartition(key)
  64. if err != nil {
  65. return err
  66. }
  67. var keyBytes []byte
  68. var valBytes []byte
  69. if key != nil {
  70. keyBytes, err = key.Encode()
  71. if err != nil {
  72. return err
  73. }
  74. }
  75. valBytes, err = value.Encode()
  76. if err != nil {
  77. return err
  78. }
  79. broker, err := p.client.Leader(p.topic, partition)
  80. if err != nil {
  81. return err
  82. }
  83. request := &ProduceRequest{RequiredAcks: p.config.RequiredAcks, Timeout: p.config.Timeout}
  84. request.AddMessage(p.topic, partition, &Message{Codec: p.config.Compression, Key: keyBytes, Value: valBytes})
  85. response, err := broker.Produce(p.client.id, request)
  86. switch err {
  87. case nil:
  88. break
  89. case EncodingError:
  90. return err
  91. default:
  92. if !retry {
  93. return err
  94. }
  95. p.client.disconnectBroker(broker)
  96. return p.safeSendMessage(key, value, false)
  97. }
  98. if response == nil {
  99. return nil
  100. }
  101. block := response.GetBlock(p.topic, partition)
  102. if block == nil {
  103. return IncompleteResponse
  104. }
  105. switch block.Err {
  106. case NoError:
  107. return nil
  108. case UnknownTopicOrPartition, NotLeaderForPartition, LeaderNotAvailable:
  109. if !retry {
  110. return block.Err
  111. }
  112. err = p.client.RefreshTopicMetadata(p.topic)
  113. if err != nil {
  114. return err
  115. }
  116. return p.safeSendMessage(key, value, false)
  117. }
  118. return block.Err
  119. }