simple_producer.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package sarama
  2. // SimpleProducer publishes Kafka messages. It routes messages to the correct broker, refreshing metadata as appropriate,
  3. // and parses responses for errors. You must call Close() on a producer to avoid leaks, it may not be garbage-collected automatically when
  4. // it passes out of scope (this is in addition to calling Close on the underlying client, which is still necessary).
  5. type SimpleProducer struct {
  6. producer *Producer
  7. topic string
  8. }
  9. // NewSimpleProducer creates a new SimpleProducer using the given client, topic and partitioner. If the
  10. // partitioner is nil, messages are partitioned by the hash of the key
  11. // (or randomly if there is no key).
  12. func NewSimpleProducer(client *Client, topic string, partitioner PartitionerConstructor) (*SimpleProducer, error) {
  13. if topic == "" {
  14. return nil, ConfigurationError("Empty topic")
  15. }
  16. config := NewProducerConfig()
  17. config.AckSuccesses = true
  18. if partitioner != nil {
  19. config.Partitioner = partitioner
  20. }
  21. prod, err := NewProducer(client, config)
  22. if err != nil {
  23. return nil, err
  24. }
  25. return &SimpleProducer{prod, topic}, nil
  26. }
  27. // SendMessage produces a message with the given key and value. To send strings as either key or value, see the StringEncoder type.
  28. func (sp *SimpleProducer) SendMessage(key, value Encoder) error {
  29. sp.producer.Input() <- &MessageToSend{Topic: sp.topic, Key: key, Value: value}
  30. // we always get one or the other because AckSuccesses is true
  31. select {
  32. case err := <-sp.producer.Errors():
  33. return err.Err
  34. case <-sp.producer.Successes():
  35. return nil
  36. }
  37. }
  38. // Close shuts down the producer and flushes any messages it may have buffered. You must call this function before
  39. // a producer object passes out of scope, as it may otherwise leak memory. You must call this before calling Close
  40. // on the underlying client.
  41. func (sp *SimpleProducer) Close() error {
  42. return sp.producer.Close()
  43. }