producer.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  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 = RandomPartitioner{}
  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. choice := p.config.Partitioner.Partition(key, len(partitions))
  56. if choice >= len(partitions) {
  57. return -1, InvalidPartition
  58. }
  59. return partitions[choice], nil
  60. }
  61. func (p *Producer) safeSendMessage(key, value Encoder, retry bool) error {
  62. partition, err := p.choosePartition(key)
  63. if err != nil {
  64. return err
  65. }
  66. var keyBytes []byte
  67. var valBytes []byte
  68. if key != nil {
  69. keyBytes, err = key.Encode()
  70. if err != nil {
  71. return err
  72. }
  73. }
  74. valBytes, err = value.Encode()
  75. if err != nil {
  76. return err
  77. }
  78. broker, err := p.client.leader(p.topic, partition)
  79. if err != nil {
  80. return err
  81. }
  82. request := &ProduceRequest{RequiredAcks: p.config.RequiredAcks, Timeout: p.config.Timeout}
  83. request.AddMessage(p.topic, partition, &Message{Codec: p.config.Compression, Key: keyBytes, Value: valBytes})
  84. response, err := broker.Produce(p.client.id, request)
  85. switch err {
  86. case nil:
  87. break
  88. case EncodingError:
  89. return err
  90. default:
  91. if !retry {
  92. return err
  93. }
  94. p.client.disconnectBroker(broker)
  95. return p.safeSendMessage(key, value, false)
  96. }
  97. if response == nil {
  98. return nil
  99. }
  100. block := response.GetBlock(p.topic, partition)
  101. if block == nil {
  102. return IncompleteResponse
  103. }
  104. switch block.Err {
  105. case NO_ERROR:
  106. return nil
  107. case UNKNOWN_TOPIC_OR_PARTITION, NOT_LEADER_FOR_PARTITION, LEADER_NOT_AVAILABLE:
  108. if !retry {
  109. return block.Err
  110. }
  111. err = p.client.refreshTopic(p.topic)
  112. if err != nil {
  113. return err
  114. }
  115. return p.safeSendMessage(key, value, false)
  116. }
  117. return block.Err
  118. }