simple_producer.go 1.9 KB

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