config.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. package sarama
  2. import "time"
  3. // Config is used to pass multiple configuration options to Sarama's constructors.
  4. type Config struct {
  5. // Net is the namespace for network-level properties used by the Broker, and shared by the Client/Producer/Consumer.
  6. Net struct {
  7. MaxOpenRequests int // How many outstanding requests a connection is allowed to have before sending on it blocks (default 5).
  8. // All three of the below configurations are similar to the `socket.timeout.ms` setting in JVM kafka.
  9. DialTimeout time.Duration // How long to wait for the initial connection to succeed before timing out and returning an error (default 30s).
  10. ReadTimeout time.Duration // How long to wait for a response before timing out and returning an error (default 30s).
  11. WriteTimeout time.Duration // How long to wait for a transmit to succeed before timing out and returning an error (default 30s).
  12. }
  13. // Metadata is the namespace for metadata management properties used by the Client, and shared by the Producer/Consumer.
  14. Metadata struct {
  15. Retry struct {
  16. Max int // The total number of times to retry a metadata request when the cluster is in the middle of a leader election (default 3).
  17. Backoff time.Duration // How long to wait for leader election to occur before retrying (default 250ms). Similar to the JVM's `retry.backoff.ms`.
  18. }
  19. // How frequently to refresh the cluster metadata in the background. Defaults to 10 minutes.
  20. // Set to 0 to disable. Similar to `topic.metadata.refresh.interval.ms` in the JVM version.
  21. RefreshFrequency time.Duration
  22. }
  23. // Producer is the namespace for configuration related to producing messages, used by the Producer.
  24. Producer struct {
  25. // The maximum permitted size of a message (defaults to 1000000). Should be set equal to or smaller than the broker's `message.max.bytes`.
  26. MaxMessageBytes int
  27. // The level of acknowledgement reliability needed from the broker (defaults to WaitForLocal).
  28. // Equivalent to the `request.required.acks` setting of the JVM producer.
  29. RequiredAcks RequiredAcks
  30. // The maximum duration the broker will wait the receipt of the number of RequiredAcks (defaults to 10 seconds).
  31. // This is only relevant when RequiredAcks is set to WaitForAll or a number > 1. Only supports millisecond resolution,
  32. // nanoseconds will be truncated. Equivalent to the JVM producer's `request.timeout.ms` setting.
  33. Timeout time.Duration
  34. // The type of compression to use on messages (defaults to no compression). Similar to `compression.codec` setting of the JVM producer.
  35. Compression CompressionCodec
  36. // Generates partitioners for choosing the partition to send messages to (defaults to hashing the message key).
  37. // Similar to the `partitioner.class` setting for the JVM producer.
  38. Partitioner PartitionerConstructor
  39. // If enabled, successfully delivered messages will be returned on the Successes channel (default disabled).
  40. AckSuccesses bool
  41. // The following config options control how often messages are batched up and sent to the broker. By default,
  42. // messages are sent as fast as possible, and all messages received while the current batch is in-flight are placed
  43. // into the subsequent batch.
  44. Flush struct {
  45. Bytes int // The best-effort number of bytes needed to trigger a flush. Use the global sarama.MaxRequestSize to set a hard upper limit.
  46. Messages int // The best-effort number of messages needed to trigger a flush. Use `MaxMessages` to set a hard upper limit.
  47. Frequency time.Duration // The best-effort frequency of flushes. Equivalent to `queue.buffering.max.ms` setting of JVM producer.
  48. // The maximum number of messages the producer will send in a single broker request.
  49. // Defaults to 0 for unlimited. Similar to `queue.buffering.max.messages` in the JVM producer.
  50. MaxMessages int
  51. }
  52. Retry struct {
  53. // The total number of times to retry sending a message (default 3).
  54. // Similar to the `message.send.max.retries` setting of the JVM producer.
  55. Max int
  56. // How long to wait for the cluster to settle between retries (default 100ms).
  57. // Similar to the `retry.backoff.ms` setting of the JVM producer.
  58. Backoff time.Duration
  59. }
  60. }
  61. // Consumer is the namespace for configuration related to consuming messages, used by the Consumer.
  62. Consumer struct {
  63. // Fetch is the namespace for controlling how many bytes are retrieved by any given request.
  64. Fetch struct {
  65. // The minimum number of message bytes to fetch in a request - the broker will wait until at least this many are available.
  66. // The default is 1, as 0 causes the consumer to spin when no messages are available. Equivalent to the JVM's `fetch.min.bytes`.
  67. Min int32
  68. // The default number of message bytes to fetch from the broker in each request (default 32768). This should be larger than the
  69. // majority of your messages, or else the consumer will spend a lot of time negotiating sizes and not actually consuming. Similar
  70. // to the JVM's `fetch.message.max.bytes`.
  71. Default int32
  72. // The maximum number of message bytes to fetch from the broker in a single request. Messages larger than this will return
  73. // ErrMessageTooLarge and will not be consumable, so you must be sure this is at least as large as your largest message.
  74. // Defaults to 0 (no limit). Similar to the JVM's `fetch.message.max.bytes`. The global `sarama.MaxResponseSize` still applies.
  75. Max int32
  76. }
  77. // The maximum amount of time the broker will wait for Consumer.Fetch.Min bytes to become available before it
  78. // returns fewer than that anyways. The default is 250ms, since 0 causes the consumer to spin when no events are available.
  79. // 100-500ms is a reasonable range for most cases. Kafka only supports precision up to milliseconds; nanoseconds will be truncated.
  80. // Equivalent to the JVM's `fetch.wait.max.ms`.
  81. MaxWaitTime time.Duration
  82. }
  83. // A user-provided string sent with every request to the brokers for logging, debugging, and auditing purposes.
  84. // Defaults to "sarama", but you should probably set it to something specific to your application.
  85. ClientID string
  86. // The number of events to buffer in internal and external channels. This permits the producer and consumer to
  87. // continue processing some messages in the background while user code is working, greatly improving throughput.
  88. // Defaults to 256.
  89. ChannelBufferSize int
  90. }
  91. // NewConfig returns a new configuration instance with sane defaults.
  92. func NewConfig() *Config {
  93. c := &Config{}
  94. c.Net.MaxOpenRequests = 5
  95. c.Net.DialTimeout = 30 * time.Second
  96. c.Net.ReadTimeout = 30 * time.Second
  97. c.Net.WriteTimeout = 30 * time.Second
  98. c.Metadata.Retry.Max = 3
  99. c.Metadata.Retry.Backoff = 250 * time.Millisecond
  100. c.Metadata.RefreshFrequency = 10 * time.Minute
  101. c.Producer.MaxMessageBytes = 1000000
  102. c.Producer.RequiredAcks = WaitForLocal
  103. c.Producer.Timeout = 10 * time.Second
  104. c.Producer.Partitioner = NewHashPartitioner
  105. c.Producer.Retry.Max = 3
  106. c.Producer.Retry.Backoff = 100 * time.Millisecond
  107. c.Consumer.Fetch.Min = 1
  108. c.Consumer.Fetch.Default = 32768
  109. c.Consumer.MaxWaitTime = 250 * time.Millisecond
  110. c.ChannelBufferSize = 256
  111. return c
  112. }
  113. // Validate checks a Config instance. It will return a
  114. // ConfigurationError if the specified values don't make sense.
  115. func (c *Config) Validate() error {
  116. // some configuration values should be warned on but not fail completely, do those first
  117. if c.Producer.RequiredAcks > 1 {
  118. Logger.Println("Producer.RequiredAcks > 1 is deprecated and will raise an exception with kafka >= 0.8.2.0.")
  119. }
  120. if c.Producer.MaxMessageBytes >= forceFlushThreshold() {
  121. Logger.Println("Producer.MaxMessageBytes is too close to MaxRequestSize; it will be ignored.")
  122. }
  123. if c.Producer.Flush.Bytes >= forceFlushThreshold() {
  124. Logger.Println("Producer.Flush.Bytes is too close to MaxRequestSize; it will be ignored.")
  125. }
  126. if c.Producer.Timeout%time.Millisecond != 0 {
  127. Logger.Println("Producer.Timeout only supports millisecond resolution; nanoseconds will be truncated.")
  128. }
  129. if c.Consumer.MaxWaitTime < 100*time.Millisecond {
  130. Logger.Println("Consumer.MaxWaitTime is very low, which can cause high CPU and network usage. See documentation for details.")
  131. }
  132. if c.Consumer.MaxWaitTime%time.Millisecond != 0 {
  133. Logger.Println("Consumer.MaxWaitTime only supports millisecond precision; nanoseconds will be truncated.")
  134. }
  135. if c.ClientID == "sarama" {
  136. Logger.Println("ClientID is the default of 'sarama', you should consider setting it to something application-specific.")
  137. }
  138. // validate Net values
  139. switch {
  140. case c.Net.MaxOpenRequests <= 0:
  141. return ConfigurationError("Invalid Net.MaxOpenRequests, must be > 0")
  142. case c.Net.DialTimeout <= 0:
  143. return ConfigurationError("Invalid Net.DialTimeout, must be > 0")
  144. case c.Net.ReadTimeout <= 0:
  145. return ConfigurationError("Invalid Net.ReadTimeout, must be > 0")
  146. case c.Net.WriteTimeout <= 0:
  147. return ConfigurationError("Invalid Net.WriteTimeout, must be > 0")
  148. }
  149. // validate the Metadata values
  150. switch {
  151. case c.Metadata.Retry.Max < 0:
  152. return ConfigurationError("Invalid Metadata.Retry.Max, must be >= 0")
  153. case c.Metadata.Retry.Backoff <= time.Duration(0):
  154. return ConfigurationError("Invalid Metadata.Retry.Backoff, must be > 0")
  155. case c.Metadata.RefreshFrequency < time.Duration(0):
  156. return ConfigurationError("Invalid Metadata.RefreshFrequency, must be >= 0")
  157. }
  158. // validate the Produce values
  159. switch {
  160. case c.Producer.MaxMessageBytes <= 0:
  161. return ConfigurationError("Invalid Producer.MaxMessageBytes, must be > 0")
  162. case c.Producer.RequiredAcks < -1:
  163. return ConfigurationError("Invalid Producer.RequiredAcks, must be >= -1")
  164. case c.Producer.Timeout <= 0:
  165. return ConfigurationError("Invalid Producer.Timeout, must be > 0")
  166. case c.Producer.Partitioner == nil:
  167. return ConfigurationError("Invalid Producer.Partitioner, must not be nil")
  168. case c.Producer.Flush.Bytes < 0:
  169. return ConfigurationError("Invalid Producer.Flush.Bytes, must be >= 0")
  170. case c.Producer.Flush.Messages < 0:
  171. return ConfigurationError("Invalid Producer.Flush.Messages, must be >= 0")
  172. case c.Producer.Flush.Frequency < 0:
  173. return ConfigurationError("Invalid Producer.Flush.Frequency, must be >= 0")
  174. case c.Producer.Flush.MaxMessages < 0:
  175. return ConfigurationError("Invalid Producer.Flush.MaxMessages, must be >= 0")
  176. case c.Producer.Flush.MaxMessages > 0 && c.Producer.Flush.MaxMessages < c.Producer.Flush.Messages:
  177. return ConfigurationError("Invalid Producer.Flush.MaxMessages, must be >= Producer.Flush.Messages when set")
  178. case c.Producer.Retry.Max < 0:
  179. return ConfigurationError("Invalid Producer.MaxRetries, must be >= 0")
  180. case c.Producer.Retry.Backoff < 0:
  181. return ConfigurationError("Invalid Producer.RetryBackoff, must be >= 0")
  182. }
  183. // validate the Consume values
  184. switch {
  185. case c.Consumer.Fetch.Min <= 0:
  186. return ConfigurationError("Invalid Consumer.Fetch.Min, must be > 0")
  187. case c.Consumer.Fetch.Default <= 0:
  188. return ConfigurationError("Invalid Consumer.Fetch.Default, must be > 0")
  189. case c.Consumer.Fetch.Max < 0:
  190. return ConfigurationError("Invalid Consumer.Fetch.Max, must be >= 0")
  191. case c.Consumer.MaxWaitTime < 1*time.Millisecond:
  192. return ConfigurationError("Invalid Consumer.MaxWaitTime, must be > 1ms")
  193. }
  194. // validate misc shared values
  195. switch {
  196. case c.ChannelBufferSize < 0:
  197. return ConfigurationError("Invalid ChannelBufferSize, must be >= 0")
  198. }
  199. return nil
  200. }