Kafka
Since Camel 2.13
Both producer and consumer are supported
The Kafka component is used for communicating with Apache Kafka message broker.
Maven users will need to add the following dependency to their pom.xml for this component.
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-kafka</artifactId>
<version>x.x.x</version>
<!-- use the same version as your Camel core version -->
</dependency> Configuring Options
Camel components are configured on two separate levels:
-
component level
-
endpoint level
Configuring Component Options
At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.
For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.
Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.
You can configure components using:
-
the Component DSL.
-
in a configuration file (
application.properties,*.yamlfiles, etc). -
directly in the Java code.
Configuring Endpoint Options
You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.
Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.
A good practice when configuring options is to use Property Placeholders.
Property placeholders provide a few benefits:
-
They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.
-
They allow externalizing the configuration from the code.
-
They help the code to become more flexible and reusable.
The following two sections list all the options, firstly for the component followed by the endpoint.
Component Options
The Kafka component supports the following options which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
Sets additional properties for either kafka consumer or kafka producer in case they can’t be set directly on the camel configurations (e.g.: new Kafka properties that are not reflected yet in Camel configurations), the properties have to be prefixed with additionalProperties., e.g.: additionalProperties.transactional.id=12345&additionalProperties.schema.registry.url=http://localhost:8811/avro. If the properties are set in the application.properties file, they must be prefixed with camel.component.kafka.additional-properties (camel.component.kafka-share.additional-properties for the Kafka Share component) followed by the property name enclosed in square brackets, for example the delivery.timeout.ms property in square brackets. When sslContextParameters is configured, additional properties whose names start with ssl. are ignored because that SSL context configures the complete TLS engine. This is a multi-value option with prefix: additionalProperties. | Map | ||
URL of the Kafka brokers to use. The format is host1:port1,host2:port2, and the list can be a subset of brokers or a VIP pointing to a subset of brokers. This option is known as bootstrap.servers in the Kafka documentation. | String | ||
The client id is a user-specified string sent in each request to help trace calls. It should logically identify the application making the request. | String | ||
Allows to pre-configure the Kafka component with common options that the endpoints will reuse. | KafkaConfiguration | ||
Close idle connections after the number of milliseconds specified by this config. | 540000 | Integer | |
Enables Kafka read-process-write exactly-once mode. On the source endpoint, also configure allowManualCommit=true, autoCommitEnable=false, breakOnFirstError=true and an explicit, non-blank groupId. On the destination endpoint, configure an explicit transactionalId base that is unique to this Camel runtime instance and stable across restarts. Camel appends the owning route id so producers in different routes do not share a Kafka transactional id. transacted=true without an explicit transactional id is not sufficient for exactly-once mode. | false | boolean | |
To use a custom HeaderFilterStrategy to filter header to and from Camel message. | HeaderFilterStrategy | ||
The period of time in milliseconds after which we force a refresh of metadata even if we haven’t seen any partition leadership changes to proactively discover any new brokers or partitions. | 300000 | Integer | |
A list of classes to use as metrics reporters. Implementing the org.apache.kafka.common.metrics.MetricsReporter interface allows plugging in classes that will be notified of new metric creation. When custom reporters are set and org.apache.kafka.common.metrics.JmxReporter is needed, it has to be explicitly added to the list. | String | ||
The window of time a metrics sample is computed over. | 30000 | Integer | |
The number of samples maintained to compute metrics. | 2 | Integer | |
The size of the TCP receive buffer (SO_RCVBUF) to use when reading data. If the value is -1, the OS default will be used. | 65536 | Integer | |
The maximum amount of time in milliseconds to wait when reconnecting to a broker that has repeatedly failed to connect. If provided, the backoff per host will increase exponentially for each consecutive connection failure, up to this maximum. After calculating the backoff increase, 20% random jitter is added to avoid connection storms. | 1000 | Integer | |
The base amount of time to wait before attempting to reconnect to a given host. This avoids repeatedly connecting to a host in a tight loop. This backoff applies to all connection attempts by the client to a broker. This value is the initial backoff value and will increase exponentially for each consecutive connection failure, up to the reconnectBackoffMaxMs value. | 50 | Integer | |
The maximum amount of time in milliseconds to wait when retrying a request to the broker that has repeatedly failed. If provided, the backoff per client will increase exponentially for each failed request, up to this maximum. To prevent all clients from being synchronized upon retry, a randomized jitter with a factor of 0.2 will be applied to the backoff, resulting in the backoff falling within a range between 20% below and 20% above the computed value. If retry.backoff.ms is set to be higher than retry.backoff.max.ms, then retry.backoff.max.ms will be used as a constant backoff from the beginning without any exponential increase. | 1000 | Integer | |
The amount of time to wait before attempting to retry a failed request to a given topic partition. This avoids repeatedly sending requests in a tight loop under some failure scenarios. This value is the initial backoff value and will increase exponentially for each failed request, up to the retry.backoff.max.ms value. | 100 | Integer | |
The size of the TCP send buffer (SO_SNDBUF) to use when sending data. If the value is -1, the OS default will be used. | 131072 | Integer | |
Timeout in milliseconds to wait gracefully for the consumer or producer to shut down and terminate its worker threads. | 30000 | int | |
Whether to allow manual commits with KafkaManualCommit. If enabled, the consumer stores a KafkaManualCommit in the CamelKafkaManualCommit header of each exchange (in batching mode, the one of the last record), and the route calls its commit() method to commit the offset of the record. Disable autoCommitEnable too, otherwise the Kafka consumer also commits the offsets in the background. How commit() commits is set by kafkaManualCommitFactory. | false | boolean | |
Whether the Kafka consumer commits the offsets periodically in the background (enable.auto.commit), every autoCommitIntervalMs. Camel turns it off when offsetRepository is set or batching is enabled. When off, the offsets are committed by the route with allowManualCommit, by Camel to the offsetRepository, or by Camel after each batch in batching mode; otherwise no offsets are committed. | true | boolean | |
The frequency in milliseconds that the consumer offsets are auto-committed to Kafka if autoCommitEnable is set to true. | 5000 | Integer | |
Where a consumer group starts reading when it has no committed offset, or the committed offset is out of range. Valid values are: earliest (seek to the earliest available offset), latest (seek to the latest offset, the default), none (throw an exception if no previous offset is found), by_duration: followed by an ISO-8601 duration (e.g. by_duration:PT5M or by_duration:P1D; requires Kafka 4.0 or later). | latest | String | |
Whether the consumer processes the records in batches instead of one exchange per record. The body of a batch exchange is a List with the exchanges of the records. A batch is processed when it has maxPollRecords records, when batchingIntervalMs has passed, or when a poll returns no records and pollTimeoutMs has passed since the batch was started. Batching turns off the Kafka auto commit: unless allowManualCommit or offsetRepository is set, Camel commits the offsets of a batch asynchronously when its exchange completes successfully. | false | boolean | |
In batching mode, the time in milliseconds after which an incomplete batch (fewer than maxPollRecords records) is processed. The check is done after each poll, so the batch is processed up to pollTimeoutMs later: with 10000 and the default pollTimeoutMs of 5000, an incomplete batch is processed after 10 to 15 seconds. If not set, an incomplete batch is processed only when a poll returns no records and pollTimeoutMs has passed since the batch was started. | Integer | ||
Whether the consumer stops at the first exchange that fails (an exception that the error handler did not handle) and consumes that record again. If false, the consumer logs the failure with the exceptionHandler and goes on with the next record. If true, Camel commits the offsets of the records before the failed record (with allowManualCommit, only when kafkaManualCommitFactory is DefaultKafkaManualCommitFactory or DefaultKafkaManualAsyncCommitFactory; without it, only with offsetRepository; otherwise nothing is committed), closes the Kafka consumer and creates a new one, which polls again from the committed offset: the failed record is consumed again, and so are the records after the last commit. A record that always fails is consumed again and again, so handle such errors with the Camel error handler. In batching mode, nothing is committed with allowManualCommit, and without it the failed batch is committed, so it is not consumed again. | false | boolean | |
Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | |
Automatically check the CRC32 of the records consumed. This ensures no on-the-wire or on-disk corruption to the messages occurred. This check adds some overhead, so it may be disabled in cases seeking extreme performance. | true | Boolean | |
The maximum time, in milliseconds, that a synchronous commit (commitSync) waits for the broker: the commit() of KafkaManualCommit with the default or the DefaultKafkaManualCommitFactory, and the commit of breakOnFirstError with that factory. When it expires, the commit fails with org.apache.kafka.common.errors.TimeoutException. | 5000 | Long | |
The configuration controls the maximum amount of time the client will wait for the response of a request. If the response is not received before the timeout elapsed, the client will resend the request if necessary or fail the request if retries are exhausted. | 30000 | Integer | |
The number of Kafka consumers that the endpoint runs, each on its own thread with its own connection to the brokers. They are members of the same consumer group, so they share the partitions of the topic: the consumers beyond the number of partitions (counting the consumers of all the application instances) get no records. With groupInstanceId, each consumer gets its own group instance id. | 1 | int | |
The maximum amount of data the server should return for a fetch request. This is not an absolute maximum, if the first message in the first non-empty partition of the fetch is larger than this value, the message will still be returned to ensure that the consumer can make progress. The maximum message size accepted by the broker is defined via message.max.bytes (broker config) or max.message.bytes (topic config). Note that the consumer performs multiple fetches in parallel. | 52428800 | Integer | |
The minimum amount of data the server should return for a fetch request. If insufficient data is available, the request will wait for that much data to accumulate before answering the request. | 1 | Integer | |
The maximum time, in milliseconds, that the server blocks before answering a fetch request when there isn’t enough data to immediately satisfy fetchMinBytes. | 500 | Integer | |
A string that uniquely identifies the group of consumer processes to which this consumer belongs. By setting the same group id, multiple processes can indicate that they are all part of the same consumer group. It takes precedence over a group.id set in additionalProperties. If neither is set, the consumer uses a generated group id, a new one at each start, and logs a WARN: it does not resume from the offsets committed before a restart, and each instance of the application receives every record. Set it on a consumer that must resume after a restart or share the records with other instances. | String | ||
A unique identifier of the consumer instance provided by the end user. Only non-empty strings are permitted. If set, the consumer is treated as a static member, which means that only one instance with this ID is allowed in the consumer group at any time. This can be used in combination with a larger session timeout to avoid group rebalances caused by transient unavailability (e.g., process restarts). If not set, the consumer will join the group as a dynamic member, which is the traditional behavior. When consumersCount is greater than 1, each consumer is a static member of its own, with this ID followed by a dash and the index of the consumer (myId-0, myId-1, …). | String | ||
The consumer group protocol to use. The classic protocol uses the traditional partition assignment and rebalancing mechanism. The consumer protocol enables the new KIP-848 consumer rebalance protocol which provides faster and more efficient rebalancing. When set to consumer, classic-only properties (heartbeatIntervalMs, sessionTimeoutMs, partitionAssignor) are automatically excluded from the consumer configuration. Enum values:
| classic | String | |
The name of the server-side assignor to use when groupProtocol is set to consumer. If not specified, the group coordinator uses the default assignor configured on the broker (group.consumer.assignors). | String | ||
To use a custom KafkaHeaderDeserializer to deserialize kafka headers values. | KafkaHeaderDeserializer | ||
The expected time between heartbeats to the consumer coordinator when using Kafka’s group management facilities. Heartbeats are used to ensure that the consumer’s session stays active and to facilitate rebalancing when new consumers join or leave the group. This option is only used when groupProtocol is set to classic. In that case, the value must be set lower than sessionTimeoutMs, but typically should be set no higher than 1/3 of that value. It can be adjusted even lower to control the expected time for normal rebalances. When groupProtocol is set to consumer, the heartbeat interval is controlled by the broker with group.consumer.heartbeat.interval.ms, and this option is left out of the consumer configuration. | 3000 | Integer | |
Deserializer class for the key that implements the Deserializer interface. | org.apache.kafka.common.serialization.StringDeserializer | String | |
The maximum amount of data per-partition the server will return. This is not an absolute maximum, if the first record batch in the first non-empty partition of the fetch is larger than this value, the batch will still be returned to ensure that the consumer can make progress. The maximum record batch size accepted by the broker is defined via message.max.bytes (broker config) or max.message.bytes (topic config). See fetchMaxBytes for limiting the consumer request size. | 1048576 | Integer | |
The maximum delay between invocations of poll() when using consumer group management. This places an upper bound on the amount of time that the consumer can be idle before fetching more records. If poll() is not called before expiration of this timeout, then the consumer is considered failed, and the group will re-balance to reassign the partitions to another member. | 300000 | Integer | |
The maximum number of records returned in a single call to poll(). It does not change how much data the consumer fetches from the brokers. In batching mode, it is also the maximum number of records in a batch. | 500 | Integer | |
The repository (a StateRepository) in which the consumer stores the offset of each partition, under the key topic/partition, after it has processed the records of the partition. When a partition is assigned, the consumer seeks to the stored offset, so it resumes after the last stored record. Setting it turns off the Kafka auto commit, and without allowManualCommit the offsets are not committed to Kafka. seekTo is not used when it is set. | StateRepository | ||
The class names of the partition assignment strategies, ordered by preference, that the client will use to distribute partition ownership amongst consumer instances when group management is used. Multiple class names can be separated by comma. If not set, the Kafka default is used: org.apache.kafka.clients.consumer.RangeAssignor and org.apache.kafka.clients.consumer.CooperativeStickyAssignor. This uses the RangeAssignor, but allows upgrading to the CooperativeStickyAssignor with a single rolling restart that removes the RangeAssignor from the list. This option is only used when groupProtocol is set to classic. | String | ||
What to do when the Kafka consumer throws an exception while polling, for example for a record that cannot be deserialized. DISCARD logs it and polls again. ERROR_HANDLER routes the exception to the Camel error handler of the route and polls again, but stops the consumer on an authentication or authorization error. RECONNECT closes the Kafka consumer and creates a new one, which polls again from the committed offset, but stops the consumer on an authentication error. RETRY polls again with the same Kafka consumer. STOP stops the consumer: restart the route to consume again. DISCARD and ERROR_HANDLER skip a record that cannot be deserialized (the consumer seeks to the next offset); the other exceptions do not move the offsets. Not used when the component has a pollExceptionStrategy or a pollExceptionStrategyFactory. Enum values:
| ERROR_HANDLER | PollOnError | |
The maximum time, in milliseconds, that each poll() of the Kafka consumer waits for records when none are available. In batching mode, an incomplete batch is also processed when a poll returns no records and this time has passed since the batch was started. | 5000 | Long | |
Whether to eager validate that broker host:port is valid and can be DNS resolved to known host during starting this consumer. If the validation fails, then an exception is thrown, which makes Camel fail fast. Disabling this will postpone the validation after the consumer is started, and Camel will keep re-connecting in case of validation or DNS resolution error. | true | boolean | |
Seeks the consumer to the beginning (BEGINNING) or to the end (END) of each partition that is assigned to it, regardless of the committed offset: BEGINNING reads all the records of the partition again, END skips the records that are already there. The seek is done on every partition assignment: when the consumer starts, after a rebalance, and when the consumer reconnects (for example after breakOnFirstError or with pollOnError RECONNECT). Not used when offsetRepository is set. Enum values:
| SeekPolicy | ||
The timeout used to detect client failures when using Kafka’s group management facility. The client sends periodic heartbeats to indicate its liveness to the broker. If no heartbeats are received by the broker before the expiration of this session timeout, then the broker will remove this client from the group and initiate a rebalance. Note that the value must be in the allowable range as configured in the broker configuration by group.min.session.timeout.ms and group.max.session.timeout.ms. This option is only used when groupProtocol is set to classic. When groupProtocol is set to consumer, the session timeout is controlled by the broker with group.consumer.session.timeout.ms, and this option is left out of the consumer configuration. | 45000 | Integer | |
This enables the use of a specific Avro reader for use with the in multiple Schema registries documentation with Avro Deserializers implementation. This option is only available externally (not standard Apache Kafka). When schemaRegistryVendor is set, it is set under the property of the vendor (for apicurio apicurio.registry.use-specific-avro-reader, for aws-glue avroRecordType=SPECIFIC_RECORD). | false | boolean | |
Whether the topic is a regular expression (java.util.regex.Pattern): the consumer subscribes to every topic whose name matches it, also to the topics created later, which the Kafka consumer finds when it refreshes its metadata (see metadataMaxAgeMs). | false | boolean | |
Deserializer class for value that implements the Deserializer interface. | org.apache.kafka.common.serialization.StringDeserializer | String | |
The delay in milliseconds between two attempts to create the Kafka consumer (see createConsumerBackoffMaxAttempts). | 5000 | long | |
The maximum number of attempts to create and subscribe the Kafka consumer of a consumer thread (also when it is created again after a reconnect), after which Camel gives up and terminates that consumer thread. Creating the consumer fails both for temporary causes, such as a broker host name that cannot be resolved yet, and for lasting ones, such as an invalid configuration, and the Kafka client does not tell them apart. 0 (the default) or a negative value retries forever. To try again after Camel gave up, restart the route. | int | ||
Controls how to read messages written transactionally. If set to read_committed, consumer.poll() will only return transactional messages which have been committed. If set to read_uncommitted (the default), consumer.poll() will return all messages, even transactional messages which have been aborted. Non-transactional messages will be returned unconditionally in either mode. Messages will always be returned in offset order. Hence, in read_committed mode, consumer.poll() will only return messages up to the last stable offset (LSO), which is the one less than the offset of the first open transaction. In particular, any messages appearing after messages belonging to ongoing transactions will be withheld until the relevant transaction has been completed. As a result, read_committed consumers will not be able to read up to the high watermark when there are in flight transactions. Further, when in read_committed the seekToEnd method will return the LSO. Enum values:
| read_uncommitted | String | |
Autowired The factory that creates the KafkaManualCommit of each exchange when allowManualCommit is enabled, which also selects how the offsets are committed. With DefaultKafkaManualCommitFactory, commit() commits synchronously (commitSync). With DefaultKafkaManualAsyncCommitFactory, commit() records the offset and the consumer thread commits it asynchronously (commitAsync) before its next poll, so commit() can be called from another thread. With these two, breakOnFirstError also commits the records before the failed record (not in batching mode). When not set, commit() commits synchronously. When not set, or with a custom factory (which creates custom KafkaManualCommit instances), Camel commits no offsets of its own, also not for breakOnFirstError. | KafkaManualCommitFactory | ||
Autowired A custom PollExceptionStrategy that decides how the consumer handles an exception thrown while polling records, instead of pollOnError. One instance is shared by all consumer threads; pollExceptionStrategyFactory takes precedence. Only used by the kafka component. | PollExceptionStrategy | ||
Autowired Factory to create a PollExceptionStrategy per Kafka consumer fetch thread. Unlike the pollExceptionStrategy option, which shares a single strategy across all consumer threads, the factory is invoked each time a fetch thread creates its Kafka consumer (on start and on every reconnect), so each thread gets its own strategy bound to its current consumer. This is required by strategies that drive the consumer (such as the built-in reconnect, stop, and bridge strategies), and it also works correctly when an endpoint uses multiple consumer threads. The factory may be called concurrently and must be thread-safe. | PollExceptionStrategyFactory | ||
Deprecated Deprecated: this option has no effect. Use createConsumerBackoffInterval instead. | 5000 | long | |
Deprecated Deprecated: this option has no effect. Use createConsumerBackoffMaxAttempts instead. | int | ||
Whether the consumer checks, after it has subscribed, that the topic exists on the brokers (with topicIsPattern, that a topic matches the pattern), and fails if it does not. The failure is retried as set by createConsumerBackoffMaxAttempts and createConsumerBackoffInterval. If false, the consumer also subscribes to a topic that does not exist, and receives its records once it is created. | false | boolean | |
When the producer sends each element of an Iterable or Iterator body as a record (see useIterator), whether the Kafka headers of the record of an element that is an Exchange or a Message are made from the headers of that element. If false, every record gets the headers of the message that holds the body. | false | boolean | |
The total bytes of memory the producer can use to buffer records waiting to be sent to the server. If records are sent faster than they can be delivered to the server, the producer will block for maxBlockMs after which it will fail with an exception. This setting should correspond roughly to the total memory the producer will use, but is not a hard bound since not all memory the producer uses is used for buffering. Some additional memory will be used for compression (if compression is enabled) as well as for maintaining in-flight requests. | 33554432 | Integer | |
This parameter allows you to specify the compression codec for all data generated by this producer. Valid values are none, gzip, snappy, lz4 and zstd. Enum values:
| none | String | |
An upper bound on the time to report success or failure after a call to send() returns. This limits the total time that a record will be delayed prior to sending, the time to await acknowledgement from the broker (if expected), and the time allowed for retriable send failures. The producer may report failure to send a record earlier than this config if either an unrecoverable error is encountered, the retries have been exhausted, or the record is added to a batch which reached an earlier delivery expiration deadline. The value of this config should be greater than or equal to the sum of requestTimeoutMs and lingerMs. | 120000 | Integer | |
When set to 'true', the producer will ensure that exactly one copy of each message is written in the stream. If 'false', producer retries due to broker failures, etc., may write duplicates of the retried message in the stream. Note that enabling idempotence requires max.in.flight.requests.per.connection to be less than or equal to 5 (with message ordering preserved for any allowable value), retries to be greater than 0, and acks must be 'all'. Idempotence is enabled by default if no conflicting configurations are set. If conflicting configurations are set and idempotence is not explicitly enabled, idempotence is disabled. If idempotence is explicitly enabled and conflicting configurations are set, a ConfigException is thrown. | true | boolean | |
The KafkaHeaderSerializer that converts the values of the Camel headers that the headerFilterStrategy lets through into the values of the Kafka record headers. The default DefaultKafkaHeaderSerializer writes a String or a Boolean as text, a Long, Integer or Double as its bytes, keeps a byte[], converts other values to byte[] with the Camel type converter, and leaves out a header that it cannot convert. | KafkaHeaderSerializer | ||
The key of the records, converted for the keySerializer. It takes precedence over the CamelKafkaKey header, except for an element of an Iterable body (see useIterator) that is an Exchange or a Message with that header. | String | ||
The serializer class for keys. It must implement the org.apache.kafka.common.serialization.Serializer interface. | org.apache.kafka.common.serialization.StringSerializer | String | |
Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | |
The producer groups together any records that arrive in between request transmissions into a single, batched, request. Normally, this occurs only under load when records arrive faster than they can be sent out. However, in some circumstances, the client may want to reduce the number of requests even under a moderate load. This setting achieves this by adding a small amount of artificial delay. That is, rather than immediately sending out a record, the producer will wait for up to the given delay to allow other records to be sent so that they can be batched together. This can be thought of as analogous to Nagle’s algorithm in TCP. This setting gives the upper bound on the delay for batching: once we get producerBatchSize worth of records for a partition, it will be sent immediately regardless of this setting, however, if we have fewer than this many bytes accumulated for this partition, we will 'linger' for the specified time waiting for more records to show up. This setting defaults to 5 (i.e., 5ms delay). Increasing it to 50, for example, would have the effect of reducing the number of requests sent but would add up to 50ms of latency to records sent in the absence of load. The default changed from 0 to 5 in Apache Kafka 4.0 as the efficiency gains from larger batches typically result in similar or lower producer latency despite the increased linger. | 5 | Integer | |
The configuration controls how long the KafkaProducer’s send(), partitionsFor(), initTransactions(), sendOffsetsToTransaction(), commitTransaction() and abortTransaction() methods will block. For send() this timeout bounds the total time waiting for both metadata fetch and buffer allocation (blocking in the user-supplied serializers or partitioner is not counted against this timeout). For partitionsFor() this time out bounds the time spent waiting for metadata if it is unavailable. The transaction-related methods always block, but may time out if the transaction coordinator could not be discovered or did not respond within the timeout. | 60000 | Integer | |
The maximum number of unacknowledged requests the client will send on a single connection before blocking. Note that if this setting is set to be greater than 1 and enableIdempotence is set to false, there is a risk of message reordering after a failed send due to retries (i.e., if retries are enabled); if retries are disabled or if enableIdempotence is set to true, ordering will be preserved. Additionally, enabling idempotence requires the value of this setting to be less than or equal to 5, because the broker only retains at most 5 batches for each producer. If the value is more than 5, previous batches may be removed on the broker side. | 5 | Integer | |
The maximum size of a request in bytes. This setting will limit the number of record batches the producer will send in a single request to avoid sending huge requests. This is also effectively a cap on the maximum uncompressed record batch size. Note that the server has its own cap on the record batch size (after compression if compression is enabled) which may be different from this. | 1048576 | Integer | |
The partitioner class that determines which partition to send a record to. If not set, the default partitioning logic is used: a record with a key goes to a partition chosen by a hash of the key, and a record without a key goes to a sticky partition that changes when at least producerBatchSize bytes have been produced to it. A custom partitioner implements the org.apache.kafka.clients.producer.Partitioner interface. | String | ||
Whether the default partitioning logic ignores the record keys (partitioner.ignore.keys): if true, a record with a key goes to a partition as a record without a key does, instead of to the partition of the hash of its key. No effect when partitioner is set. | false | boolean | |
The partition to send the records to. It takes precedence over the CamelKafkaPartitionKey header. If neither is set, the partitioner chooses the partition. | Integer | ||
The producer will attempt to batch records together into fewer requests whenever multiple records are being sent to the same partition. This helps performance on both the client and the server. This configuration controls the default batch size in bytes. No attempt will be made to batch records larger than this size. Requests sent to brokers will contain multiple batches, one for each partition with data available to be sent. A small batch size will make batching less common and may reduce throughput (a batch size of zero will disable batching entirely). A very large batch size may use memory a bit more wastefully as we will always allocate a buffer of the specified batch size in anticipation of additional records. | 16384 | Integer | |
Deprecated Deprecated: this option has no effect. Use bufferMemorySize or maxBlockMs instead. | 10000 | Integer | |
The number of acknowledgments the producer requires the leader to have received before considering a request complete. This controls the durability of records that are sent. The following settings are allowed: acks=0 If set to zero, then the producer will not wait for any acknowledgment from the server at all. The record will be immediately added to the socket buffer and considered sent. No guarantee can be made that the server has received the record in this case, and the retry configuration will not take effect (as the client won’t generally know of any failures). The offset given back for each record will always be set to -1. acks=1 This will mean the leader will write the record to its local log but will respond without awaiting full acknowledgment from all followers. In this case should the leader fail immediately after acknowledging the record, but before the followers have replicated it, then the record will be lost. acks=all This means the leader will wait for the full set of in-sync replicas to acknowledge the record. This guarantees that the record will not be lost as long as at least one in-sync replica remains alive. This is the strongest available guarantee. This is equivalent to the acks=-1 setting. Note that enabling idempotence requires this config value to be 'all'. If conflicting configurations are set and idempotence is not explicitly enabled, idempotence is disabled. Enum values:
| all | String | |
The configuration controls the maximum amount of time the client will wait for the response of a request. If the response is not received before the timeout elapses, the client will resend the request if necessary or fail the request if retries are exhausted. This should be larger than replica.lag.time.max.ms (a broker configuration) to reduce the possibility of message duplication due to unnecessary producer retries. | 30000 | Integer | |
Number of times to retry a request that fails with a transient error. Setting a value greater than zero will cause the client to resend any record whose send fails with a potentially transient error. Requests will be retried this many times until they succeed, fail with a non-transient error, or the deliveryTimeoutMs expires. Note that this automatic retry will simply resend the same record upon receiving the error. Setting a value of zero will disable this automatic retry behaviour, so that the transient errors will be propagated to the application to be handled. Users should generally prefer to leave this config unset and instead use deliveryTimeoutMs to control retry behavior. Enabling idempotence requires this config value to be greater than 0. If conflicting configurations are set and idempotence is not explicitly enabled, idempotence is disabled. Allowing retries while setting enable.idempotence to false and max.in.flight.requests.per.connection to greater than 1 will potentially change the ordering of records, because if two batches are sent to a single partition, and the first fails and is retried but the second succeeds; then the records in the second batch may appear first. | Integer | ||
Whether the producer is transactional, with a transactional.id that Camel makes from the id of the endpoint (endpoint followed by a number, in the order in which Camel creates the endpoints) and the route id. Each exchange sends its records in a Kafka transaction that is committed when the exchange completes, or aborted when it fails. Set transactionalId for an id that stays the same across restarts. Not used when transactionalId or the transactional.id additional property is set. | false | boolean | |
The transactional.id of the producer, which makes it a transactional producer: each exchange sends its records in a Kafka transaction that is committed when the exchange completes, or aborted when it fails. Use an id that is unique to the producer and stays the same across restarts. When it is set, transacted is not used. With exactlyOnce, Camel appends the route id. | String | ||
Sets whether sending to kafka should send the message body as a single record, or use a java.util.Iterator to send multiple records to kafka (if the message body can be iterated). A Jackson JSON array node is sent as one record per element, and any other JSON node (such as an object) as one record. | true | boolean | |
The serializer class for values (the message body). It must implement the org.apache.kafka.common.serialization.Serializer interface. | org.apache.kafka.common.serialization.StringSerializer | String | |
The thread pool on which the producer continues routing the exchange after Kafka has acknowledged the records (the send callback runs on the I/O thread of the Kafka producer, which must not route). Only used when synchronous is disabled. Camel does not shut down a pool set here: you manage its lifecycle. If not set, the producer creates a pool with workerPoolCoreSize and workerPoolMaxSize threads. | ExecutorService | ||
The number of core threads of the worker pool that the producer creates when workerPool is not set, on which it continues routing the exchange after Kafka has acknowledged the records. | 10 | Integer | |
The maximum number of threads of the worker pool that the producer creates when workerPool is not set, on which it continues routing the exchange after Kafka has acknowledged the records. | 20 | Integer | |
Whether the producer stores the RecordMetadata (topic, partition, offset and timestamp) that Kafka returns for the records it sent, as a List of RecordMetadata in the CamelKafkaRecordMeta header. With an Iterable body (see useIterator), the list has the metadata of every record, and each element that is an Exchange or a Message gets the metadata of its own record in the same header. | false | boolean | |
Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc. | true | boolean | |
Autowired The factory that creates the Kafka clients (org.apache.kafka.clients.consumer.KafkaConsumer and org.apache.kafka.clients.producer.KafkaProducer) from the properties of the endpoint, and gives their bootstrap servers, for example to create clients that extend the Kafka clients. The default DefaultKafkaClientFactory creates the Kafka clients and uses the brokers option. | KafkaClientFactory | ||
Whether the producer sends synchronously: the routing thread sends the records and waits until Kafka has acknowledged them, and no worker pool is used. If false, the producer is asynchronous: the routing of the exchange continues on the worker pool when Kafka has acknowledged the records. | false | boolean | |
Used for enabling or disabling all consumer based health checks from this component. | true | boolean | |
Used for enabling or disabling all producer based health checks from this component. Notice: Camel has by default disabled all producer based health-checks. You can turn on producer checks globally by setting camel.health.producersEnabled=true. | true | boolean | |
Comma-separated class names of Kafka interceptors (interceptor.classes), set on both the Kafka producer and the Kafka consumer of the endpoint. A producer interceptor implements org.apache.kafka.clients.producer.ProducerInterceptor, a consumer interceptor org.apache.kafka.clients.consumer.ConsumerInterceptor. A Kafka client fails to start (KafkaException) when the list has an interceptor of the other kind, so use it on an endpoint that only produces or only consumes. | String | ||
The format of the record values in the schema registry, which selects the serializer and deserializer of the schemaRegistryVendor. Not every vendor supports every format: azure supports only avro. Only used when schemaRegistryVendor is set. Enum values:
| avro | String | |
URL of the schema registry servers to use. The format is host1:port1,host2:port2. This is known as schema.registry.url in multiple Schema registries documentation. This option is only available externally (not standard Apache Kafka). When schemaRegistryVendor is set, the URL is set under the property of the vendor: schema.registry.url for confluent, apicurio.registry.url for apicurio (the URL of the registry API, such as http://localhost:8080/apis/registry/v3), schema.registry.url for azure (the fully qualified namespace, such as my-namespace.servicebus.windows.net), and endpoint for aws-glue (optional, as Glue is addressed by the AWS region). | String | ||
The schema registry vendor, which sets up the value serializer (producer), the value deserializer (consumer) and the registry properties of the vendor for the schemaFormat, so that you do not need to know the class names or the property names of the vendor. The schemaRegistryURL is set as the registry URL of the vendor. A valueSerializer or valueDeserializer other than the default, and additionalProperties, take precedence. The serde jars of the vendor must be on the classpath, as Camel does not include them. Leave it unset to configure the serializer, deserializer and registry properties yourself. Enum values:
| String | ||
Login thread sleep time between refresh attempts. | 60000 | Integer | |
Location of the kerberos config file. | String | ||
Kerberos kinit command path. Default is /usr/bin/kinit. | /usr/bin/kinit | String | |
A list of rules for mapping from principal names to short names (typically operating system usernames). The rules are evaluated in order, and the first rule that matches a principal name is used to map it to a short name. Any later rules in the list are ignored. By default, principal names made of a username, a hostname and a Kerberos realm are mapped to the username. For more details on the format, please see the Security Authorization and ACLs documentation (at the Apache Kafka project website). Multiple values can be separated by comma. | DEFAULT | String | |
Percentage of random jitter added to the renewal time. | 0.05 | Double | |
Login thread will sleep until the specified window factor of time from last refresh to ticket’s expiry has been reached, at which time it will try to renew the ticket. | 0.8 | Double | |
OAuth client ID. Used when saslAuthType is set to OAUTH. | String | ||
OAuth client secret. Used when saslAuthType is set to OAUTH. | String | ||
OAuth scope. Used when saslAuthType is set to OAUTH. | String | ||
OAuth token endpoint URI. Used when saslAuthType is set to OAUTH. | String | ||
Simplified authentication type to use. This provides an easier way to configure Kafka authentication without manually setting securityProtocol, saslMechanism, and saslJaasConfig. When set, the appropriate security settings are automatically derived. Note: This is optional. You can still use the traditional approach with explicit securityProtocol, saslMechanism, and saslJaasConfig properties. Enum values:
| KafkaAuthType | ||
Expose the kafka sasl.jaas.config parameter Example: org.apache.kafka.common.security.plain.PlainLoginModule required username=USERNAME password=PASSWORD;. | String | ||
The Kerberos principal name that Kafka runs as. This can be defined either in Kafka’s JAAS config or in Kafka’s config. | String | ||
The Simple Authentication and Security Layer (SASL) Mechanism used. For the valid values see http://www.iana.org/assignments/sasl-mechanisms/sasl-mechanisms.xhtml. | GSSAPI | String | |
Password for SASL authentication. Used when saslAuthType is set to PLAIN, SCRAM_SHA_256, or SCRAM_SHA_512. | String | ||
Username for SASL authentication. Used when saslAuthType is set to PLAIN, SCRAM_SHA_256, or SCRAM_SHA_512. | String | ||
The OAuth2 client id to log in to the schema registry with client credentials. Used with schemaRegistryVendor confluent and apicurio. | String | ||
The OAuth2 client secret to log in to the schema registry with client credentials. | String | ||
The OAuth2 scope to ask for when logging in to the schema registry with client credentials (optional). | String | ||
The token endpoint of the OAuth2 server to log in to the schema registry with client credentials, with schemaRegistryOauthClientId and schemaRegistryOauthClientSecret. Used with schemaRegistryVendor confluent (bearer.auth.issuer.endpoint.url) and apicurio (apicurio.registry.auth.service.token.endpoint, such as the token endpoint of a Keycloak realm). | String | ||
The password to log in to the schema registry with basic auth, with schemaRegistryUsername. For Confluent Cloud, the API secret. | String | ||
The username to log in to the schema registry with basic auth, with schemaRegistryPassword. Used with schemaRegistryVendor confluent (basic.auth.user.info, which is the API key for Confluent Cloud) and apicurio (apicurio.registry.auth.username). The azure and aws-glue vendors log in with the credentials of the environment instead. | String | ||
Protocol used to communicate with brokers. SASL_PLAINTEXT, PLAINTEXT, SASL_SSL and SSL are supported. | PLAINTEXT | String | |
A list of cipher suites. This is a named combination of authentication, encryption, MAC and key exchange algorithm used to negotiate the security settings for a network connection using TLS or SSL network protocol. By default, all the available cipher suites are supported. | String | ||
SSL configuration using a Camel SSLContextParameters object. When configured, Camel creates Kafka TLS engines with its own SslEngineFactory and this SSL context. It takes precedence over the other SSL endpoint options and additionalProperties entries whose names start with ssl.; only sslEndpointAlgorithm remains applicable for broker hostname verification. | SSLContextParameters | ||
The list of protocols enabled for SSL connections. The default is TLSv1.2,TLSv1.3. This means that clients and servers will prefer TLSv1.3 if both support it and fallback to TLSv1.2 otherwise (assuming both support at least TLSv1.2). This default should be fine for most use cases. Also see the documentation of sslProtocol to understand how it can impact the TLS version negotiation behavior. | TLSv1.2,TLSv1.3 | String | |
The endpoint identification algorithm to validate server hostname using server certificate. Use none or false to disable server hostname verification. | https | String | |
The algorithm used by key manager factory for SSL connections. Default value is the key manager factory algorithm configured for the Java Virtual Machine. | SunX509 | String | |
The password of the private key in the key store file or the PEM key specified in sslKeystoreKey. This is required for clients only if two-way authentication is configured. | String | ||
The location of the key store file. This is optional for the client and can be used for two-way authentication for the client. | String | ||
The store password for the key store file. This is optional for the client and only needed if sslKeystoreLocation is configured. Key store password is not supported for PEM format. | String | ||
The file format of the key store file. This is optional for the client. The supported values are JKS, PKCS12 and PEM. | JKS | String | |
The SSL protocol used to generate the SSLContext. The default is TLSv1.3, which should be fine for most use cases. A typical alternative to the default is TLSv1.2. Allowed values for this config are dependent on the JVM. Clients using the defaults for this config and sslEnabledProtocols will downgrade to TLSv1.2 if the server does not support TLSv1.3. If this config is set to TLSv1.2, however, clients will not use TLSv1.3 even if it is one of the values in sslEnabledProtocols and the server only supports TLSv1.3. | TLSv1.3 | String | |
The name of the security provider used for SSL connections. Default value is the default security provider of the JVM. | String | ||
The algorithm used by trust manager factory for SSL connections. Default value is the trust manager factory algorithm configured for the Java Virtual Machine. | PKIX | String | |
The location of the trust store file. | String | ||
The password for the trust store file. If a password is not set, trust store file configured will still be used, but integrity checking is disabled. Trust store password is not supported for PEM format. | String | ||
The file format of the trust store file. The supported values are JKS, PKCS12 and PEM. | JKS | String | |
Whether to use the global SSL context parameters of the CamelContext when the endpoint has no sslContextParameters. | false | boolean |
Endpoint Options
The Kafka endpoint is configured using URI syntax:
kafka:topic
With the following path and query parameters:
Query Parameters
| Name | Description | Default | Type |
|---|---|---|---|
Sets additional properties for either kafka consumer or kafka producer in case they can’t be set directly on the camel configurations (e.g.: new Kafka properties that are not reflected yet in Camel configurations), the properties have to be prefixed with additionalProperties., e.g.: additionalProperties.transactional.id=12345&additionalProperties.schema.registry.url=http://localhost:8811/avro. If the properties are set in the application.properties file, they must be prefixed with camel.component.kafka.additional-properties (camel.component.kafka-share.additional-properties for the Kafka Share component) followed by the property name enclosed in square brackets, for example the delivery.timeout.ms property in square brackets. When sslContextParameters is configured, additional properties whose names start with ssl. are ignored because that SSL context configures the complete TLS engine. This is a multi-value option with prefix: additionalProperties. | Map | ||
URL of the Kafka brokers to use. The format is host1:port1,host2:port2, and the list can be a subset of brokers or a VIP pointing to a subset of brokers. This option is known as bootstrap.servers in the Kafka documentation. | String | ||
The client id is a user-specified string sent in each request to help trace calls. It should logically identify the application making the request. | String | ||
Close idle connections after the number of milliseconds specified by this config. | 540000 | Integer | |
Enables Kafka read-process-write exactly-once mode. On the source endpoint, also configure allowManualCommit=true, autoCommitEnable=false, breakOnFirstError=true and an explicit, non-blank groupId. On the destination endpoint, configure an explicit transactionalId base that is unique to this Camel runtime instance and stable across restarts. Camel appends the owning route id so producers in different routes do not share a Kafka transactional id. transacted=true without an explicit transactional id is not sufficient for exactly-once mode. | false | boolean | |
To use a custom HeaderFilterStrategy to filter header to and from Camel message. | HeaderFilterStrategy | ||
The period of time in milliseconds after which we force a refresh of metadata even if we haven’t seen any partition leadership changes to proactively discover any new brokers or partitions. | 300000 | Integer | |
A list of classes to use as metrics reporters. Implementing the org.apache.kafka.common.metrics.MetricsReporter interface allows plugging in classes that will be notified of new metric creation. When custom reporters are set and org.apache.kafka.common.metrics.JmxReporter is needed, it has to be explicitly added to the list. | String | ||
The window of time a metrics sample is computed over. | 30000 | Integer | |
The number of samples maintained to compute metrics. | 2 | Integer | |
The size of the TCP receive buffer (SO_RCVBUF) to use when reading data. If the value is -1, the OS default will be used. | 65536 | Integer | |
The maximum amount of time in milliseconds to wait when reconnecting to a broker that has repeatedly failed to connect. If provided, the backoff per host will increase exponentially for each consecutive connection failure, up to this maximum. After calculating the backoff increase, 20% random jitter is added to avoid connection storms. | 1000 | Integer | |
The base amount of time to wait before attempting to reconnect to a given host. This avoids repeatedly connecting to a host in a tight loop. This backoff applies to all connection attempts by the client to a broker. This value is the initial backoff value and will increase exponentially for each consecutive connection failure, up to the reconnectBackoffMaxMs value. | 50 | Integer | |
The maximum amount of time in milliseconds to wait when retrying a request to the broker that has repeatedly failed. If provided, the backoff per client will increase exponentially for each failed request, up to this maximum. To prevent all clients from being synchronized upon retry, a randomized jitter with a factor of 0.2 will be applied to the backoff, resulting in the backoff falling within a range between 20% below and 20% above the computed value. If retry.backoff.ms is set to be higher than retry.backoff.max.ms, then retry.backoff.max.ms will be used as a constant backoff from the beginning without any exponential increase. | 1000 | Integer | |
The amount of time to wait before attempting to retry a failed request to a given topic partition. This avoids repeatedly sending requests in a tight loop under some failure scenarios. This value is the initial backoff value and will increase exponentially for each failed request, up to the retry.backoff.max.ms value. | 100 | Integer | |
The size of the TCP send buffer (SO_SNDBUF) to use when sending data. If the value is -1, the OS default will be used. | 131072 | Integer | |
Timeout in milliseconds to wait gracefully for the consumer or producer to shut down and terminate its worker threads. | 30000 | int | |
Whether to allow manual commits with KafkaManualCommit. If enabled, the consumer stores a KafkaManualCommit in the CamelKafkaManualCommit header of each exchange (in batching mode, the one of the last record), and the route calls its commit() method to commit the offset of the record. Disable autoCommitEnable too, otherwise the Kafka consumer also commits the offsets in the background. How commit() commits is set by kafkaManualCommitFactory. | false | boolean | |
Whether the Kafka consumer commits the offsets periodically in the background (enable.auto.commit), every autoCommitIntervalMs. Camel turns it off when offsetRepository is set or batching is enabled. When off, the offsets are committed by the route with allowManualCommit, by Camel to the offsetRepository, or by Camel after each batch in batching mode; otherwise no offsets are committed. | true | boolean | |
The frequency in milliseconds that the consumer offsets are auto-committed to Kafka if autoCommitEnable is set to true. | 5000 | Integer | |
Where a consumer group starts reading when it has no committed offset, or the committed offset is out of range. Valid values are: earliest (seek to the earliest available offset), latest (seek to the latest offset, the default), none (throw an exception if no previous offset is found), by_duration: followed by an ISO-8601 duration (e.g. by_duration:PT5M or by_duration:P1D; requires Kafka 4.0 or later). | latest | String | |
Whether the consumer processes the records in batches instead of one exchange per record. The body of a batch exchange is a List with the exchanges of the records. A batch is processed when it has maxPollRecords records, when batchingIntervalMs has passed, or when a poll returns no records and pollTimeoutMs has passed since the batch was started. Batching turns off the Kafka auto commit: unless allowManualCommit or offsetRepository is set, Camel commits the offsets of a batch asynchronously when its exchange completes successfully. | false | boolean | |
In batching mode, the time in milliseconds after which an incomplete batch (fewer than maxPollRecords records) is processed. The check is done after each poll, so the batch is processed up to pollTimeoutMs later: with 10000 and the default pollTimeoutMs of 5000, an incomplete batch is processed after 10 to 15 seconds. If not set, an incomplete batch is processed only when a poll returns no records and pollTimeoutMs has passed since the batch was started. | Integer | ||
Whether the consumer stops at the first exchange that fails (an exception that the error handler did not handle) and consumes that record again. If false, the consumer logs the failure with the exceptionHandler and goes on with the next record. If true, Camel commits the offsets of the records before the failed record (with allowManualCommit, only when kafkaManualCommitFactory is DefaultKafkaManualCommitFactory or DefaultKafkaManualAsyncCommitFactory; without it, only with offsetRepository; otherwise nothing is committed), closes the Kafka consumer and creates a new one, which polls again from the committed offset: the failed record is consumed again, and so are the records after the last commit. A record that always fails is consumed again and again, so handle such errors with the Camel error handler. In batching mode, nothing is committed with allowManualCommit, and without it the failed batch is committed, so it is not consumed again. | false | boolean | |
Automatically check the CRC32 of the records consumed. This ensures no on-the-wire or on-disk corruption to the messages occurred. This check adds some overhead, so it may be disabled in cases seeking extreme performance. | true | Boolean | |
The maximum time, in milliseconds, that a synchronous commit (commitSync) waits for the broker: the commit() of KafkaManualCommit with the default or the DefaultKafkaManualCommitFactory, and the commit of breakOnFirstError with that factory. When it expires, the commit fails with org.apache.kafka.common.errors.TimeoutException. | 5000 | Long | |
The configuration controls the maximum amount of time the client will wait for the response of a request. If the response is not received before the timeout elapsed, the client will resend the request if necessary or fail the request if retries are exhausted. | 30000 | Integer | |
The number of Kafka consumers that the endpoint runs, each on its own thread with its own connection to the brokers. They are members of the same consumer group, so they share the partitions of the topic: the consumers beyond the number of partitions (counting the consumers of all the application instances) get no records. With groupInstanceId, each consumer gets its own group instance id. | 1 | int | |
The maximum amount of data the server should return for a fetch request. This is not an absolute maximum, if the first message in the first non-empty partition of the fetch is larger than this value, the message will still be returned to ensure that the consumer can make progress. The maximum message size accepted by the broker is defined via message.max.bytes (broker config) or max.message.bytes (topic config). Note that the consumer performs multiple fetches in parallel. | 52428800 | Integer | |
The minimum amount of data the server should return for a fetch request. If insufficient data is available, the request will wait for that much data to accumulate before answering the request. | 1 | Integer | |
The maximum time, in milliseconds, that the server blocks before answering a fetch request when there isn’t enough data to immediately satisfy fetchMinBytes. | 500 | Integer | |
A string that uniquely identifies the group of consumer processes to which this consumer belongs. By setting the same group id, multiple processes can indicate that they are all part of the same consumer group. It takes precedence over a group.id set in additionalProperties. If neither is set, the consumer uses a generated group id, a new one at each start, and logs a WARN: it does not resume from the offsets committed before a restart, and each instance of the application receives every record. Set it on a consumer that must resume after a restart or share the records with other instances. | String | ||
A unique identifier of the consumer instance provided by the end user. Only non-empty strings are permitted. If set, the consumer is treated as a static member, which means that only one instance with this ID is allowed in the consumer group at any time. This can be used in combination with a larger session timeout to avoid group rebalances caused by transient unavailability (e.g., process restarts). If not set, the consumer will join the group as a dynamic member, which is the traditional behavior. When consumersCount is greater than 1, each consumer is a static member of its own, with this ID followed by a dash and the index of the consumer (myId-0, myId-1, …). | String | ||
The consumer group protocol to use. The classic protocol uses the traditional partition assignment and rebalancing mechanism. The consumer protocol enables the new KIP-848 consumer rebalance protocol which provides faster and more efficient rebalancing. When set to consumer, classic-only properties (heartbeatIntervalMs, sessionTimeoutMs, partitionAssignor) are automatically excluded from the consumer configuration. Enum values:
| classic | String | |
The name of the server-side assignor to use when groupProtocol is set to consumer. If not specified, the group coordinator uses the default assignor configured on the broker (group.consumer.assignors). | String | ||
To use a custom KafkaHeaderDeserializer to deserialize kafka headers values. | KafkaHeaderDeserializer | ||
The expected time between heartbeats to the consumer coordinator when using Kafka’s group management facilities. Heartbeats are used to ensure that the consumer’s session stays active and to facilitate rebalancing when new consumers join or leave the group. This option is only used when groupProtocol is set to classic. In that case, the value must be set lower than sessionTimeoutMs, but typically should be set no higher than 1/3 of that value. It can be adjusted even lower to control the expected time for normal rebalances. When groupProtocol is set to consumer, the heartbeat interval is controlled by the broker with group.consumer.heartbeat.interval.ms, and this option is left out of the consumer configuration. | 3000 | Integer | |
Deserializer class for the key that implements the Deserializer interface. | org.apache.kafka.common.serialization.StringDeserializer | String | |
The maximum amount of data per-partition the server will return. This is not an absolute maximum, if the first record batch in the first non-empty partition of the fetch is larger than this value, the batch will still be returned to ensure that the consumer can make progress. The maximum record batch size accepted by the broker is defined via message.max.bytes (broker config) or max.message.bytes (topic config). See fetchMaxBytes for limiting the consumer request size. | 1048576 | Integer | |
The maximum delay between invocations of poll() when using consumer group management. This places an upper bound on the amount of time that the consumer can be idle before fetching more records. If poll() is not called before expiration of this timeout, then the consumer is considered failed, and the group will re-balance to reassign the partitions to another member. | 300000 | Integer | |
The maximum number of records returned in a single call to poll(). It does not change how much data the consumer fetches from the brokers. In batching mode, it is also the maximum number of records in a batch. | 500 | Integer | |
The repository (a StateRepository) in which the consumer stores the offset of each partition, under the key topic/partition, after it has processed the records of the partition. When a partition is assigned, the consumer seeks to the stored offset, so it resumes after the last stored record. Setting it turns off the Kafka auto commit, and without allowManualCommit the offsets are not committed to Kafka. seekTo is not used when it is set. | StateRepository | ||
The class names of the partition assignment strategies, ordered by preference, that the client will use to distribute partition ownership amongst consumer instances when group management is used. Multiple class names can be separated by comma. If not set, the Kafka default is used: org.apache.kafka.clients.consumer.RangeAssignor and org.apache.kafka.clients.consumer.CooperativeStickyAssignor. This uses the RangeAssignor, but allows upgrading to the CooperativeStickyAssignor with a single rolling restart that removes the RangeAssignor from the list. This option is only used when groupProtocol is set to classic. | String | ||
What to do when the Kafka consumer throws an exception while polling, for example for a record that cannot be deserialized. DISCARD logs it and polls again. ERROR_HANDLER routes the exception to the Camel error handler of the route and polls again, but stops the consumer on an authentication or authorization error. RECONNECT closes the Kafka consumer and creates a new one, which polls again from the committed offset, but stops the consumer on an authentication error. RETRY polls again with the same Kafka consumer. STOP stops the consumer: restart the route to consume again. DISCARD and ERROR_HANDLER skip a record that cannot be deserialized (the consumer seeks to the next offset); the other exceptions do not move the offsets. Not used when the component has a pollExceptionStrategy or a pollExceptionStrategyFactory. Enum values:
| ERROR_HANDLER | PollOnError | |
The maximum time, in milliseconds, that each poll() of the Kafka consumer waits for records when none are available. In batching mode, an incomplete batch is also processed when a poll returns no records and this time has passed since the batch was started. | 5000 | Long | |
Whether to eager validate that broker host:port is valid and can be DNS resolved to known host during starting this consumer. If the validation fails, then an exception is thrown, which makes Camel fail fast. Disabling this will postpone the validation after the consumer is started, and Camel will keep re-connecting in case of validation or DNS resolution error. | true | boolean | |
Seeks the consumer to the beginning (BEGINNING) or to the end (END) of each partition that is assigned to it, regardless of the committed offset: BEGINNING reads all the records of the partition again, END skips the records that are already there. The seek is done on every partition assignment: when the consumer starts, after a rebalance, and when the consumer reconnects (for example after breakOnFirstError or with pollOnError RECONNECT). Not used when offsetRepository is set. Enum values:
| SeekPolicy | ||
The timeout used to detect client failures when using Kafka’s group management facility. The client sends periodic heartbeats to indicate its liveness to the broker. If no heartbeats are received by the broker before the expiration of this session timeout, then the broker will remove this client from the group and initiate a rebalance. Note that the value must be in the allowable range as configured in the broker configuration by group.min.session.timeout.ms and group.max.session.timeout.ms. This option is only used when groupProtocol is set to classic. When groupProtocol is set to consumer, the session timeout is controlled by the broker with group.consumer.session.timeout.ms, and this option is left out of the consumer configuration. | 45000 | Integer | |
This enables the use of a specific Avro reader for use with the in multiple Schema registries documentation with Avro Deserializers implementation. This option is only available externally (not standard Apache Kafka). When schemaRegistryVendor is set, it is set under the property of the vendor (for apicurio apicurio.registry.use-specific-avro-reader, for aws-glue avroRecordType=SPECIFIC_RECORD). | false | boolean | |
Whether the topic is a regular expression (java.util.regex.Pattern): the consumer subscribes to every topic whose name matches it, also to the topics created later, which the Kafka consumer finds when it refreshes its metadata (see metadataMaxAgeMs). | false | boolean | |
Deserializer class for value that implements the Deserializer interface. | org.apache.kafka.common.serialization.StringDeserializer | String | |
Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | |
To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | ExceptionHandler | ||
Sets the exchange pattern when the consumer creates an exchange. Enum values:
| ExchangePattern | ||
Controls how to read messages written transactionally. If set to read_committed, consumer.poll() will only return transactional messages which have been committed. If set to read_uncommitted (the default), consumer.poll() will return all messages, even transactional messages which have been aborted. Non-transactional messages will be returned unconditionally in either mode. Messages will always be returned in offset order. Hence, in read_committed mode, consumer.poll() will only return messages up to the last stable offset (LSO), which is the one less than the offset of the first open transaction. In particular, any messages appearing after messages belonging to ongoing transactions will be withheld until the relevant transaction has been completed. As a result, read_committed consumers will not be able to read up to the high watermark when there are in flight transactions. Further, when in read_committed the seekToEnd method will return the LSO. Enum values:
| read_uncommitted | String | |
The factory that creates the KafkaManualCommit of each exchange when allowManualCommit is enabled, which also selects how the offsets are committed. With DefaultKafkaManualCommitFactory, commit() commits synchronously (commitSync). With DefaultKafkaManualAsyncCommitFactory, commit() records the offset and the consumer thread commits it asynchronously (commitAsync) before its next poll, so commit() can be called from another thread. With these two, breakOnFirstError also commits the records before the failed record (not in batching mode). When not set, commit() commits synchronously. When not set, or with a custom factory (which creates custom KafkaManualCommit instances), Camel commits no offsets of its own, also not for breakOnFirstError. | KafkaManualCommitFactory | ||
When the producer sends each element of an Iterable or Iterator body as a record (see useIterator), whether the Kafka headers of the record of an element that is an Exchange or a Message are made from the headers of that element. If false, every record gets the headers of the message that holds the body. | false | boolean | |
The total bytes of memory the producer can use to buffer records waiting to be sent to the server. If records are sent faster than they can be delivered to the server, the producer will block for maxBlockMs after which it will fail with an exception. This setting should correspond roughly to the total memory the producer will use, but is not a hard bound since not all memory the producer uses is used for buffering. Some additional memory will be used for compression (if compression is enabled) as well as for maintaining in-flight requests. | 33554432 | Integer | |
This parameter allows you to specify the compression codec for all data generated by this producer. Valid values are none, gzip, snappy, lz4 and zstd. Enum values:
| none | String | |
An upper bound on the time to report success or failure after a call to send() returns. This limits the total time that a record will be delayed prior to sending, the time to await acknowledgement from the broker (if expected), and the time allowed for retriable send failures. The producer may report failure to send a record earlier than this config if either an unrecoverable error is encountered, the retries have been exhausted, or the record is added to a batch which reached an earlier delivery expiration deadline. The value of this config should be greater than or equal to the sum of requestTimeoutMs and lingerMs. | 120000 | Integer | |
When set to 'true', the producer will ensure that exactly one copy of each message is written in the stream. If 'false', producer retries due to broker failures, etc., may write duplicates of the retried message in the stream. Note that enabling idempotence requires max.in.flight.requests.per.connection to be less than or equal to 5 (with message ordering preserved for any allowable value), retries to be greater than 0, and acks must be 'all'. Idempotence is enabled by default if no conflicting configurations are set. If conflicting configurations are set and idempotence is not explicitly enabled, idempotence is disabled. If idempotence is explicitly enabled and conflicting configurations are set, a ConfigException is thrown. | true | boolean | |
The KafkaHeaderSerializer that converts the values of the Camel headers that the headerFilterStrategy lets through into the values of the Kafka record headers. The default DefaultKafkaHeaderSerializer writes a String or a Boolean as text, a Long, Integer or Double as its bytes, keeps a byte[], converts other values to byte[] with the Camel type converter, and leaves out a header that it cannot convert. | KafkaHeaderSerializer | ||
The key of the records, converted for the keySerializer. It takes precedence over the CamelKafkaKey header, except for an element of an Iterable body (see useIterator) that is an Exchange or a Message with that header. | String | ||
The serializer class for keys. It must implement the org.apache.kafka.common.serialization.Serializer interface. | org.apache.kafka.common.serialization.StringSerializer | String | |
The producer groups together any records that arrive in between request transmissions into a single, batched, request. Normally, this occurs only under load when records arrive faster than they can be sent out. However, in some circumstances, the client may want to reduce the number of requests even under a moderate load. This setting achieves this by adding a small amount of artificial delay. That is, rather than immediately sending out a record, the producer will wait for up to the given delay to allow other records to be sent so that they can be batched together. This can be thought of as analogous to Nagle’s algorithm in TCP. This setting gives the upper bound on the delay for batching: once we get producerBatchSize worth of records for a partition, it will be sent immediately regardless of this setting, however, if we have fewer than this many bytes accumulated for this partition, we will 'linger' for the specified time waiting for more records to show up. This setting defaults to 5 (i.e., 5ms delay). Increasing it to 50, for example, would have the effect of reducing the number of requests sent but would add up to 50ms of latency to records sent in the absence of load. The default changed from 0 to 5 in Apache Kafka 4.0 as the efficiency gains from larger batches typically result in similar or lower producer latency despite the increased linger. | 5 | Integer | |
The configuration controls how long the KafkaProducer’s send(), partitionsFor(), initTransactions(), sendOffsetsToTransaction(), commitTransaction() and abortTransaction() methods will block. For send() this timeout bounds the total time waiting for both metadata fetch and buffer allocation (blocking in the user-supplied serializers or partitioner is not counted against this timeout). For partitionsFor() this time out bounds the time spent waiting for metadata if it is unavailable. The transaction-related methods always block, but may time out if the transaction coordinator could not be discovered or did not respond within the timeout. | 60000 | Integer | |
The maximum number of unacknowledged requests the client will send on a single connection before blocking. Note that if this setting is set to be greater than 1 and enableIdempotence is set to false, there is a risk of message reordering after a failed send due to retries (i.e., if retries are enabled); if retries are disabled or if enableIdempotence is set to true, ordering will be preserved. Additionally, enabling idempotence requires the value of this setting to be less than or equal to 5, because the broker only retains at most 5 batches for each producer. If the value is more than 5, previous batches may be removed on the broker side. | 5 | Integer | |
The maximum size of a request in bytes. This setting will limit the number of record batches the producer will send in a single request to avoid sending huge requests. This is also effectively a cap on the maximum uncompressed record batch size. Note that the server has its own cap on the record batch size (after compression if compression is enabled) which may be different from this. | 1048576 | Integer | |
The partitioner class that determines which partition to send a record to. If not set, the default partitioning logic is used: a record with a key goes to a partition chosen by a hash of the key, and a record without a key goes to a sticky partition that changes when at least producerBatchSize bytes have been produced to it. A custom partitioner implements the org.apache.kafka.clients.producer.Partitioner interface. | String | ||
Whether the default partitioning logic ignores the record keys (partitioner.ignore.keys): if true, a record with a key goes to a partition as a record without a key does, instead of to the partition of the hash of its key. No effect when partitioner is set. | false | boolean | |
The partition to send the records to. It takes precedence over the CamelKafkaPartitionKey header. If neither is set, the partitioner chooses the partition. | Integer | ||
The producer will attempt to batch records together into fewer requests whenever multiple records are being sent to the same partition. This helps performance on both the client and the server. This configuration controls the default batch size in bytes. No attempt will be made to batch records larger than this size. Requests sent to brokers will contain multiple batches, one for each partition with data available to be sent. A small batch size will make batching less common and may reduce throughput (a batch size of zero will disable batching entirely). A very large batch size may use memory a bit more wastefully as we will always allocate a buffer of the specified batch size in anticipation of additional records. | 16384 | Integer | |
Deprecated Deprecated: this option has no effect. Use bufferMemorySize or maxBlockMs instead. | 10000 | Integer | |
The number of acknowledgments the producer requires the leader to have received before considering a request complete. This controls the durability of records that are sent. The following settings are allowed: acks=0 If set to zero, then the producer will not wait for any acknowledgment from the server at all. The record will be immediately added to the socket buffer and considered sent. No guarantee can be made that the server has received the record in this case, and the retry configuration will not take effect (as the client won’t generally know of any failures). The offset given back for each record will always be set to -1. acks=1 This will mean the leader will write the record to its local log but will respond without awaiting full acknowledgment from all followers. In this case should the leader fail immediately after acknowledging the record, but before the followers have replicated it, then the record will be lost. acks=all This means the leader will wait for the full set of in-sync replicas to acknowledge the record. This guarantees that the record will not be lost as long as at least one in-sync replica remains alive. This is the strongest available guarantee. This is equivalent to the acks=-1 setting. Note that enabling idempotence requires this config value to be 'all'. If conflicting configurations are set and idempotence is not explicitly enabled, idempotence is disabled. Enum values:
| all | String | |
The configuration controls the maximum amount of time the client will wait for the response of a request. If the response is not received before the timeout elapses, the client will resend the request if necessary or fail the request if retries are exhausted. This should be larger than replica.lag.time.max.ms (a broker configuration) to reduce the possibility of message duplication due to unnecessary producer retries. | 30000 | Integer | |
Number of times to retry a request that fails with a transient error. Setting a value greater than zero will cause the client to resend any record whose send fails with a potentially transient error. Requests will be retried this many times until they succeed, fail with a non-transient error, or the deliveryTimeoutMs expires. Note that this automatic retry will simply resend the same record upon receiving the error. Setting a value of zero will disable this automatic retry behaviour, so that the transient errors will be propagated to the application to be handled. Users should generally prefer to leave this config unset and instead use deliveryTimeoutMs to control retry behavior. Enabling idempotence requires this config value to be greater than 0. If conflicting configurations are set and idempotence is not explicitly enabled, idempotence is disabled. Allowing retries while setting enable.idempotence to false and max.in.flight.requests.per.connection to greater than 1 will potentially change the ordering of records, because if two batches are sent to a single partition, and the first fails and is retried but the second succeeds; then the records in the second batch may appear first. | Integer | ||
Whether the producer is transactional, with a transactional.id that Camel makes from the id of the endpoint (endpoint followed by a number, in the order in which Camel creates the endpoints) and the route id. Each exchange sends its records in a Kafka transaction that is committed when the exchange completes, or aborted when it fails. Set transactionalId for an id that stays the same across restarts. Not used when transactionalId or the transactional.id additional property is set. | false | boolean | |
The transactional.id of the producer, which makes it a transactional producer: each exchange sends its records in a Kafka transaction that is committed when the exchange completes, or aborted when it fails. Use an id that is unique to the producer and stays the same across restarts. When it is set, transacted is not used. With exactlyOnce, Camel appends the route id. | String | ||
Sets whether sending to kafka should send the message body as a single record, or use a java.util.Iterator to send multiple records to kafka (if the message body can be iterated). A Jackson JSON array node is sent as one record per element, and any other JSON node (such as an object) as one record. | true | boolean | |
The serializer class for values (the message body). It must implement the org.apache.kafka.common.serialization.Serializer interface. | org.apache.kafka.common.serialization.StringSerializer | String | |
The thread pool on which the producer continues routing the exchange after Kafka has acknowledged the records (the send callback runs on the I/O thread of the Kafka producer, which must not route). Only used when synchronous is disabled. Camel does not shut down a pool set here: you manage its lifecycle. If not set, the producer creates a pool with workerPoolCoreSize and workerPoolMaxSize threads. | ExecutorService | ||
The number of core threads of the worker pool that the producer creates when workerPool is not set, on which it continues routing the exchange after Kafka has acknowledged the records. | 10 | Integer | |
The maximum number of threads of the worker pool that the producer creates when workerPool is not set, on which it continues routing the exchange after Kafka has acknowledged the records. | 20 | Integer | |
Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | |
Whether the producer stores the RecordMetadata (topic, partition, offset and timestamp) that Kafka returns for the records it sent, as a List of RecordMetadata in the CamelKafkaRecordMeta header. With an Iterable body (see useIterator), the list has the metadata of every record, and each element that is an Exchange or a Message gets the metadata of its own record in the same header. | false | boolean | |
The factory that creates the Kafka clients (org.apache.kafka.clients.consumer.KafkaConsumer and org.apache.kafka.clients.producer.KafkaProducer) from the properties of the endpoint, and gives their bootstrap servers, for example to create clients that extend the Kafka clients. The default DefaultKafkaClientFactory creates the Kafka clients and uses the brokers option. | KafkaClientFactory | ||
Whether the producer sends synchronously: the routing thread sends the records and waits until Kafka has acknowledged them, and no worker pool is used. If false, the producer is asynchronous: the routing of the exchange continues on the worker pool when Kafka has acknowledged the records. | false | boolean | |
Comma-separated class names of Kafka interceptors (interceptor.classes), set on both the Kafka producer and the Kafka consumer of the endpoint. A producer interceptor implements org.apache.kafka.clients.producer.ProducerInterceptor, a consumer interceptor org.apache.kafka.clients.consumer.ConsumerInterceptor. A Kafka client fails to start (KafkaException) when the list has an interceptor of the other kind, so use it on an endpoint that only produces or only consumes. | String | ||
The format of the record values in the schema registry, which selects the serializer and deserializer of the schemaRegistryVendor. Not every vendor supports every format: azure supports only avro. Only used when schemaRegistryVendor is set. Enum values:
| avro | String | |
URL of the schema registry servers to use. The format is host1:port1,host2:port2. This is known as schema.registry.url in multiple Schema registries documentation. This option is only available externally (not standard Apache Kafka). When schemaRegistryVendor is set, the URL is set under the property of the vendor: schema.registry.url for confluent, apicurio.registry.url for apicurio (the URL of the registry API, such as http://localhost:8080/apis/registry/v3), schema.registry.url for azure (the fully qualified namespace, such as my-namespace.servicebus.windows.net), and endpoint for aws-glue (optional, as Glue is addressed by the AWS region). | String | ||
The schema registry vendor, which sets up the value serializer (producer), the value deserializer (consumer) and the registry properties of the vendor for the schemaFormat, so that you do not need to know the class names or the property names of the vendor. The schemaRegistryURL is set as the registry URL of the vendor. A valueSerializer or valueDeserializer other than the default, and additionalProperties, take precedence. The serde jars of the vendor must be on the classpath, as Camel does not include them. Leave it unset to configure the serializer, deserializer and registry properties yourself. Enum values:
| String | ||
Login thread sleep time between refresh attempts. | 60000 | Integer | |
Location of the kerberos config file. | String | ||
Kerberos kinit command path. Default is /usr/bin/kinit. | /usr/bin/kinit | String | |
A list of rules for mapping from principal names to short names (typically operating system usernames). The rules are evaluated in order, and the first rule that matches a principal name is used to map it to a short name. Any later rules in the list are ignored. By default, principal names made of a username, a hostname and a Kerberos realm are mapped to the username. For more details on the format, please see the Security Authorization and ACLs documentation (at the Apache Kafka project website). Multiple values can be separated by comma. | DEFAULT | String | |
Percentage of random jitter added to the renewal time. | 0.05 | Double | |
Login thread will sleep until the specified window factor of time from last refresh to ticket’s expiry has been reached, at which time it will try to renew the ticket. | 0.8 | Double | |
OAuth client ID. Used when saslAuthType is set to OAUTH. | String | ||
OAuth client secret. Used when saslAuthType is set to OAUTH. | String | ||
OAuth scope. Used when saslAuthType is set to OAUTH. | String | ||
OAuth token endpoint URI. Used when saslAuthType is set to OAUTH. | String | ||
Simplified authentication type to use. This provides an easier way to configure Kafka authentication without manually setting securityProtocol, saslMechanism, and saslJaasConfig. When set, the appropriate security settings are automatically derived. Note: This is optional. You can still use the traditional approach with explicit securityProtocol, saslMechanism, and saslJaasConfig properties. Enum values:
| KafkaAuthType | ||
Expose the kafka sasl.jaas.config parameter Example: org.apache.kafka.common.security.plain.PlainLoginModule required username=USERNAME password=PASSWORD;. | String | ||
The Kerberos principal name that Kafka runs as. This can be defined either in Kafka’s JAAS config or in Kafka’s config. | String | ||
The Simple Authentication and Security Layer (SASL) Mechanism used. For the valid values see http://www.iana.org/assignments/sasl-mechanisms/sasl-mechanisms.xhtml. | GSSAPI | String | |
Password for SASL authentication. Used when saslAuthType is set to PLAIN, SCRAM_SHA_256, or SCRAM_SHA_512. | String | ||
Username for SASL authentication. Used when saslAuthType is set to PLAIN, SCRAM_SHA_256, or SCRAM_SHA_512. | String | ||
The OAuth2 client id to log in to the schema registry with client credentials. Used with schemaRegistryVendor confluent and apicurio. | String | ||
The OAuth2 client secret to log in to the schema registry with client credentials. | String | ||
The OAuth2 scope to ask for when logging in to the schema registry with client credentials (optional). | String | ||
The token endpoint of the OAuth2 server to log in to the schema registry with client credentials, with schemaRegistryOauthClientId and schemaRegistryOauthClientSecret. Used with schemaRegistryVendor confluent (bearer.auth.issuer.endpoint.url) and apicurio (apicurio.registry.auth.service.token.endpoint, such as the token endpoint of a Keycloak realm). | String | ||
The password to log in to the schema registry with basic auth, with schemaRegistryUsername. For Confluent Cloud, the API secret. | String | ||
The username to log in to the schema registry with basic auth, with schemaRegistryPassword. Used with schemaRegistryVendor confluent (basic.auth.user.info, which is the API key for Confluent Cloud) and apicurio (apicurio.registry.auth.username). The azure and aws-glue vendors log in with the credentials of the environment instead. | String | ||
Protocol used to communicate with brokers. SASL_PLAINTEXT, PLAINTEXT, SASL_SSL and SSL are supported. | PLAINTEXT | String | |
A list of cipher suites. This is a named combination of authentication, encryption, MAC and key exchange algorithm used to negotiate the security settings for a network connection using TLS or SSL network protocol. By default, all the available cipher suites are supported. | String | ||
SSL configuration using a Camel SSLContextParameters object. When configured, Camel creates Kafka TLS engines with its own SslEngineFactory and this SSL context. It takes precedence over the other SSL endpoint options and additionalProperties entries whose names start with ssl.; only sslEndpointAlgorithm remains applicable for broker hostname verification. | SSLContextParameters | ||
The list of protocols enabled for SSL connections. The default is TLSv1.2,TLSv1.3. This means that clients and servers will prefer TLSv1.3 if both support it and fallback to TLSv1.2 otherwise (assuming both support at least TLSv1.2). This default should be fine for most use cases. Also see the documentation of sslProtocol to understand how it can impact the TLS version negotiation behavior. | TLSv1.2,TLSv1.3 | String | |
The endpoint identification algorithm to validate server hostname using server certificate. Use none or false to disable server hostname verification. | https | String | |
The algorithm used by key manager factory for SSL connections. Default value is the key manager factory algorithm configured for the Java Virtual Machine. | SunX509 | String | |
The password of the private key in the key store file or the PEM key specified in sslKeystoreKey. This is required for clients only if two-way authentication is configured. | String | ||
The location of the key store file. This is optional for the client and can be used for two-way authentication for the client. | String | ||
The store password for the key store file. This is optional for the client and only needed if sslKeystoreLocation is configured. Key store password is not supported for PEM format. | String | ||
The file format of the key store file. This is optional for the client. The supported values are JKS, PKCS12 and PEM. | JKS | String | |
The SSL protocol used to generate the SSLContext. The default is TLSv1.3, which should be fine for most use cases. A typical alternative to the default is TLSv1.2. Allowed values for this config are dependent on the JVM. Clients using the defaults for this config and sslEnabledProtocols will downgrade to TLSv1.2 if the server does not support TLSv1.3. If this config is set to TLSv1.2, however, clients will not use TLSv1.3 even if it is one of the values in sslEnabledProtocols and the server only supports TLSv1.3. | TLSv1.3 | String | |
The name of the security provider used for SSL connections. Default value is the default security provider of the JVM. | String | ||
The algorithm used by trust manager factory for SSL connections. Default value is the trust manager factory algorithm configured for the Java Virtual Machine. | PKIX | String | |
The location of the trust store file. | String | ||
The password for the trust store file. If a password is not set, trust store file configured will still be used, but integrity checking is disabled. Trust store password is not supported for PEM format. | String | ||
The file format of the trust store file. The supported values are JKS, PKCS12 and PEM. | JKS | String |
Message Headers
The Kafka component supports the following message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
CamelKafkaPartitionKey (producer) Constant: | The partition (0-based) to send the record to. The partitionKey option takes precedence. If neither is set, the partitioner chooses the partition. | Integer | |
CamelKafkaPartition (consumer) Constant: | The partition where the message was stored. | Integer | |
| Constant: | Required Producer: the key of the record, converted for the keySerializer. The key option takes precedence, except for an element of an Iterable body that is an Exchange or a Message with this header. The default partitioner sends the records with the same key to the same partition (unless partitionerIgnoreKeys is true). Consumer: the key of the record. The header is not set when the record has no key. | Object | |
| Constant: | The topic from where the message originated. | String | |
CamelKafkaOverrideTopic (producer) Constant: | The topic to send the record to, instead of the topic of the endpoint. The producer removes the header from the message. | String | |
| Constant: | The offset of the message. | Long | |
| Constant: | The headers of the record, as the Kafka Headers object. The headers are also mapped one by one to message headers, through the headerFilterStrategy and the headerDeserializer. | Headers | |
CamelKafkaLastRecordBeforeCommit (consumer) Constant: | Whether the record is the last record of its partition in the current poll. Only set when autoCommitEnable is false or offsetRepository is set, and not in batching mode. | Boolean | |
CamelKafkaLastPollRecord (consumer) Constant: | Whether the record is the last record of the current poll. Only set when autoCommitEnable is false, offsetRepository is set or allowManualCommit is true, and not in batching mode. | Boolean | |
CamelKafkaTimestamp (consumer) Constant: | The timestamp of the record, in milliseconds since the epoch: the create time or the log append time, as configured on the topic. | Long | |
CamelMessageTimestamp (consumer) Constant: | The timestamp of the record, in milliseconds since the epoch, the same value as the CamelKafkaTimestamp header. Message.getMessageTimestamp() returns it. | Long | |
CamelKafkaOverrideTimestamp (producer) Constant: | The timestamp of the record, in milliseconds since the epoch. If not set, the Kafka producer uses the current time. On a topic with the LogAppendTime timestamp type, the broker replaces it with its own time. The producer removes the header from the message. | Long | |
CamelKafkaRecordMeta (producer) Constant: | The RecordMetadata (topic, partition, offset and timestamp) that Kafka returned for the sent records. Only set when the recordMetadata option is true. | List | |
CamelKafkaManualCommit (consumer) Constant: | The KafkaManualCommit whose commit() method commits the offset of the record (in batching mode, the batch exchange has the one of the last record). Only set when allowManualCommit is true. | KafkaManualCommit |
Message Body
The message body at each side of the Kafka component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.
| Side | Body | Description |
|---|---|---|
Consumer |
| The value of the record: a String with the default valueDeserializer (StringDeserializer), null for a tombstone. With batching, a List of the exchanges of the records.
Not known when |
Producer input |
| The value of the record, converted for the valueSerializer: text with the default StringSerializer, so a Map or a POJO is sent as its toString(): marshal it first. With useIterator, an Iterable or an Iterator is sent as one record per element, but a Jackson JSON node only when it is an array: an object node is one record. Not known when |
Producer output |
|
The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.
Deterministic simulation tests
The consumer of the Kafka component is tested with deterministic simulation tests: the real consumer runs under a seeded virtual-time scheduler against a fake of the external system, which injects faults while the tests check invariants. A failing seed can be replayed. These are the fake worlds of the component:
| World | What it checks | Issues |
|---|---|---|
Fake: FakeKafka: a topic with one or two partitions and a consumer group (classic protocol, eager rebalance), behind the Consumer interface of KafkaClientFactory Tests: | Covers:
Faults:
Invariants:
|
The worlds and their tests are in the test sources of the component. How to run them, replay a seed and write a world is described in Running the tests and Writing a fake world.
For more information about Producer/Consumer configuration:
http://kafka.apache.org/documentation.html#newconsumerconfigs http://kafka.apache.org/documentation.html#producerconfigs
If you want to send a message to a dynamic topic then use the CamelKafkaOverrideTopic header as it is used as a one-time header that is not sent along the message, and actually is removed in the producer.
Usage
TLS with sslContextParameters
When sslContextParameters is configured, Camel creates Kafka TLS engines with its CamelSslEngineFactory and the SSLContext created from those parameters. The complete Camel JSSE configuration is applied, including key and trust managers, cipher suites, enabled protocols, named groups, signature schemes and Camel’s post-quantum named-group preference when available.
In this mode, sslContextParameters is authoritative. All Kafka-specific SSL endpoint options other than sslEndpointAlgorithm (for example, sslKeystoreLocation, sslTruststoreLocation and sslProtocol) and additionalProperties entries whose names start with ssl. are ignored. Camel logs warnings listing non-default SSL endpoint option names and ignored additional-property names, without logging their values. To use different TLS settings for a particular endpoint, configure endpoint-specific sslContextParameters. The sslEndpointAlgorithm option remains applicable and controls broker hostname verification. SASL and non-SSL additional properties continue to work.
Without sslContextParameters, Camel keeps using Kafka’s default SSL engine factory and the Kafka ssl.* endpoint options and additional properties as before.
Share groups (queues)
To consume the records of a topic like a queue, with more consumers than partitions and an acknowledgement per record, use a share group (KIP-932) with the Kafka Share component.
Consumer error handling
While kafka consumer is polling messages from the kafka broker, then errors can happen. This section describes what happens and what you can configure.
The consumer may throw exception when invoking the Kafka poll API. For example, if the message cannot be deserialized due to invalid data, and many other kinds of errors. Those errors are in the form of KafkaException which are either retriable or not. The exceptions which can be retried (RetriableException) will be retried again (with a poll timeout in between). All other kinds of exceptions are handled according to the pollOnError configuration. This configuration has the following values:
-
DISCARD will discard the message and continue to poll the next message.
-
ERROR_HANDLER will use Camel’s error handler to process the exception, and afterwards continue to poll the next message.
-
RECONNECT will re-connect the consumer and try to poll the message again.
-
RETRY will let the consumer retry polling the same message again
-
STOP will stop the consumer (it has to be manually started/restarted if the consumer should be able to consume messages again).
The default is ERROR_HANDLER, which will let Camel’s error handler (if any configured) process the caused exception. Afterwards continue to poll the next message. This behavior is similar to the bridgeErrorHandler option that Camel components have.
The pollOnError configuration applies to exceptions only. The Kafka client wraps only a RuntimeException of a deserializer in a RecordDeserializationException. A java.lang.Error, such as an ExceptionInInitializerError or NoClassDefFoundError of a deserializer whose classes cannot be loaded, fails every poll the same way. The consumer thread then logs the error, closes its Kafka consumer and terminates, and the consumer health check reports DOWN. Fix the cause (for example, a dependency version), and then restart the route or the application.
For advanced control a custom implementation of org.apache.camel.component.kafka.PollExceptionStrategy can be configured on the component level, which allows controlling which of the strategies to use for each exception.
A single PollExceptionStrategy is shared by all consumer threads of an endpoint. If the strategy must be bound to its consumer thread, for example to drive a reconnect or to wrap one of the built-in strategies, configure a org.apache.camel.component.kafka.PollExceptionStrategyFactory with the pollExceptionStrategyFactory option instead. The factory is invoked each time a consumer thread creates its Kafka consumer, so each thread gets its own strategy. Use it when the endpoint runs more than one consumer thread (consumersCount > 1), or to decorate a built-in strategy by extending org.apache.camel.component.kafka.consumer.errorhandler.DefaultPollExceptionStrategyFactory.
Consumer error handling (advanced)
By default, Camel will poll using the ERROR_HANDLER to process exceptions. How Camel handles a message that results in an exception can be altered using the breakOnFirstError attribute in the configuration. Instead of continuing to poll the next message, Camel will instead commit the offset so that the message that caused the exception will be retried. This is similar to the RETRY polling strategy above.
You can configure this on the component level, either programmatically in Java, or via configuration properties:
KafkaComponent kafka = new KafkaComponent();
kafka.setBreakOnFirstError(true);
camelContext.addComponent("kafka", kafka); Or using configuration properties:
camel.component.kafka.break-on-first-error=true It is recommended that you read the section below "Using manual commit with Kafka consumer" to understand how breakOnFirstError will work based on the CommitManager that is configured.
The Kafka idempotent repository
The camel-kafka library provides a Kafka topic-based idempotent repository. This repository stores broadcasts all changes to idempotent state (add/remove) in a Kafka topic, and populates a local in-memory cache for each repository’s process instance through event sourcing. The topic used must be unique per idempotent repository instance. The mechanism does not have any requirements about the number of topic partitions, as the repository consumes from all partitions at the same time. It also does not have any requirements about the replication factor of the topic. Each repository instance that uses the topic, (e.g., typically on different machines running in parallel) controls its own consumer group, so in a cluster of 10 Camel processes using the same topic, each will control its own offset. On startup, the instance subscribes to the topic, rewinds the offset to the beginning and rebuilds the cache to the latest state. The cache will not be considered warmed up until one poll of pollDurationMs in length returns 0 records. Startup will not be completed until either the cache has warmed up, or 30 seconds go by; if the latter happens, the idempotent repository may be in an inconsistent state until its consumer catches up to the end of the topic. Be mindful of the format of the header used for the uniqueness check. By default, it uses Strings as the data types. When using primitive numeric formats, the header must be deserialized accordingly. Check the samples below for examples.
A KafkaIdempotentRepository has the following properties:
| Property | Default | Description |
|---|---|---|
| Required The name of the Kafka topic to use to broadcast changes. (required) | |
| Required The | |
| The groupId to assign to the idempotent consumer. | |
|
| Whether to sync on startup only, or to continue syncing while Camel is running. |
|
| How many of the most recently used keys should be stored in memory (default 1000). |
|
| The poll duration of the Kafka consumer. The local caches are updated immediately. This value will affect how far behind other peers that update their caches from the topic are relative to the idempotent consumer instance that sent the cache action message. The default value of this is 100 ms. If setting this value explicitly, be aware that there is a tradeoff between the remote cache liveness and the volume of network traffic between this repository’s consumer and the Kafka brokers. The cache warmup process also depends on there being one poll that fetches nothing - this indicates that the stream has been consumed up to the current point. If the poll duration is excessively long for the rate at which messages are sent on the topic, there exists a possibility that the cache cannot be warmed up and will operate in an inconsistent state relative to its peers until it catches up. |
| Sets the properties that will be used by the Kafka producer that broadcasts changes. Overrides | |
| Sets the properties that will be used by the Kafka consumer that populates the cache from the topic. Overrides |
The repository can be instantiated by defining the topic and bootstrapServers, or the producerConfig and consumerConfig property sets can be explicitly defined to enable features such as SSL/SASL. To use, this repository must be placed in the Camel registry, either manually or by registration as a bean in Spring, as it is CamelContext aware.
Sample usage is as follows:
The KafkaIdempotentRepository bean must be registered in the Camel registry before it can be referenced by the route. |
KafkaIdempotentRepository kafkaIdempotentRepository = new KafkaIdempotentRepository("idempotent-db-inserts", "localhost:9091");
SimpleRegistry registry = new SimpleRegistry();
registry.put("insertDbIdemRepo", kafkaIdempotentRepository); <!-- simple -->
<bean id="insertDbIdemRepo"
class="org.apache.camel.processor.idempotent.kafka.KafkaIdempotentRepository">
<property name="topic" value="idempotent-db-inserts"/>
<property name="bootstrapServers" value="localhost:9091"/>
</bean>
<!-- complex -->
<bean id="insertDbIdemRepo"
class="org.apache.camel.processor.idempotent.kafka.KafkaIdempotentRepository">
<property name="topic" value="idempotent-db-inserts"/>
<property name="maxCacheSize" value="10000"/>
<property name="consumerConfig">
<props>
<prop key="bootstrap.servers">localhost:9091</prop>
</props>
</property>
<property name="producerConfig">
<props>
<prop key="bootstrap.servers">localhost:9091</prop>
</props>
</property>
</bean> -
Java
-
XML
-
YAML
from("direct:performInsert")
.idempotentConsumer(header("id")).idempotentRepository("insertDbIdemRepo")
.to("sql:INSERT INTO ...")
.end(); <route>
<from uri="direct:performInsert"/>
<idempotentConsumer idempotentRepository="insertDbIdemRepo">
<header>id</header>
<to uri="sql:INSERT INTO ..."/>
</idempotentConsumer>
</route> - route:
from:
uri: direct:performInsert
steps:
- idempotentConsumer:
idempotentRepository: "#insertDbIdemRepo"
expression:
header: id
steps:
- to:
uri: "sql:INSERT INTO ..." There are 3 alternatives to choose from when using idempotency with numeric identifiers. The first one is to use the static method numericHeader method from org.apache.camel.component.kafka.serde.KafkaSerdeHelper to perform the conversion for you:
from("direct:performInsert")
.idempotentConsumer(numericHeader("id")).idempotentRepository("insertDbIdemRepo")
.to("sql:INSERT INTO ...")
.end(); Alternatively, it is possible to use a custom serializer configured via the route URL to perform the conversion:
public class CustomHeaderDeserializer extends DefaultKafkaHeaderDeserializer {
private static final Logger LOG = LoggerFactory.getLogger(CustomHeaderDeserializer.class);
@Override
public Object deserialize(String key, byte[] value) {
if (key.equals("id")) {
BigInteger bi = new BigInteger(value);
return String.valueOf(bi.longValue());
} else {
return super.deserialize(key, value);
}
}
} Lastly, it is also possible to do so in a processor:
from("kafka:my-topic?groupId=my-group")
.process(exchange -> {
byte[] id = exchange.getIn().getHeader("id", byte[].class);
BigInteger bi = new BigInteger(id);
exchange.getIn().setHeader("id", String.valueOf(bi.longValue()));
})
.idempotentConsumer(header("id"))
.idempotentRepository("kafkaIdempotentRepository")
.to("direct:process"); Manual commits with the Kafka consumer
By default, the Kafka consumer will use auto commit, where the offset will be committed automatically in the background using a given interval.
In case you want to force manual commits, you can use KafkaManualCommit API from the Camel Exchange, stored on the message header. This requires turning on manual commits by either setting the option allowManualCommit to true on the KafkaComponent or on the endpoint, for example:
KafkaComponent kafka = new KafkaComponent();
kafka.setAutoCommitEnable(false);
kafka.setAllowManualCommit(true);
camelContext.addComponent("kafka", kafka); Or using configuration properties:
camel.component.kafka.auto-commit-enable=false
camel.component.kafka.allow-manual-commit=true By default, it uses the NoopCommitManager behind the scenes. To commit an offset, you will need to use the KafkaManualCommit from Java code such as a Camel Processor:
public void process(Exchange exchange) {
KafkaManualCommit manual =
exchange.getIn().getHeader("CamelKafkaManualCommit", KafkaManualCommit.class);
manual.commit();
} The header name is CamelKafkaManualCommit. |
The KafkaManualCommit will force a synchronous commit which will block until the commit is acknowledged on Kafka, or if it fails an exception is thrown. You can use an asynchronous commit as well by configuring the KafkaManualCommitFactory with the DefaultKafkaManualAsyncCommitFactory implementation.
Then commit() records the offset, and the consumer thread commits it before its next poll, using the Kafka asynchronous commit API. So the asynchronous commit can be called from a thread other than the consumer thread, for example after an aggregator. A commit of a record that was polled before its partition was revoked from the consumer (for example in a rebalance, also when the partition is assigned to the consumer again) or before the route was suspended and resumed is not made: the consumer reads that record again.
With the synchronous or the asynchronous commit, a partition that is revoked from the consumer (in a rebalance, or when the consumer stops) is committed only up to the last record that the route committed with KafkaManualCommit.commit(), not up to the last record that the consumer processed. A record that the route still holds, for example in an aggregation group that is not complete, is not committed for it: the records that the route did not commit are consumed again after a rebalance or a restart, so they may be processed more than once.
If you want to use a custom implementation of KafkaManualCommit then you can configure a custom KafkaManualCommitFactory on the KafkaComponent that creates instances of your custom implementation.
When configuring a consumer to use manual commit and a specific CommitManager it is important to understand how these influence the behavior of breakOnFirstError
KafkaComponent kafka = new KafkaComponent();
kafka.setAutoCommitEnable(false);
kafka.setAllowManualCommit(true);
kafka.setBreakOnFirstError(true);
kafka.setKafkaManualCommitFactory(new DefaultKafkaManualCommitFactory());
camelContext.addComponent("kafka", kafka); Or using configuration properties:
camel.component.kafka.auto-commit-enable=false
camel.component.kafka.allow-manual-commit=true
camel.component.kafka.break-on-first-error=true
camel.component.kafka.kafka-manual-commit-factory=#class:org.apache.camel.component.kafka.consumer.DefaultKafkaManualCommitFactory When the CommitManager is left to the default NoopCommitManager then breakOnFirstError will not automatically commit the offset so that the message with an error is retried. The consumer must manage that in the route using KafkaManualCommit.
When the CommitManager is changed to either the synchronous or asynchronous manager then breakOnFirstError will automatically commit the offset so that the message with an error is retried. This message will be continually retried until it can be processed without an error. The break commits the records processed before the failed one, whether the route committed them or not.
A synchronous commit must be called by the consumer thread. Certain EIPs, async or concurrent operations in the DSL continue on another thread: for example, the Aggregate EIP completes its groups on its own Aggregator thread. A synchronous commit on such a thread makes the Kafka client throw a java.util.ConcurrentModificationException with the message KafkaConsumer is not safe for multi-threaded access. Use the asynchronous commit there instead. |
Consumer groups
The groupId option sets the Kafka consumer group of the consumer. The consumers of a group share the partitions of the topic, so each record is processed by one of them. The group keeps the committed offsets: after a restart, a consumer resumes where the group stopped.
The group can also be set with the group.id Kafka property in additionalProperties (additionalProperties.group.id=my-group on the endpoint, or camel.component.kafka.additional-properties[group.id] on the component). When both groupId and the group.id property are set, groupId is used. A group.id set on the component applies to every consumer endpoint without groupId, so routes that consume the same topic share its records.
Without either, the consumer uses a generated group id, a new one at each start, and logs a WARN when it starts:
-
After a restart the consumer does not resume from the offsets committed before. It starts where
autoOffsetResetsays: with the defaultlatest, the records sent while the application was stopped are not consumed. -
Each instance of the application (for example each replica of a deployment) is a group of its own, and receives every record.
This only suits a consumer that must receive every record in each instance, from the time it starts. Set groupId on the other consumers.
Where a new consumer group starts reading
The autoOffsetReset option controls where a Kafka consumer group begins reading when it has no previously committed offset for the topic partition, or when the committed offset is no longer available on the broker (e.g. it has been deleted by retention).
autoOffsetReset is only consulted for new or reset consumer groups. If the group already has a committed offset, Kafka resumes from that offset and ignores this option entirely. Setting by_duration:PT5M does not rewind an existing consumer group by 5 minutes — it only affects the very first read of a brand-new group, or a group whose offsets have expired. |
The available values are:
latest(default)-
The consumer starts at the end of the partition (the latest offset). Messages produced before the consumer first connected are skipped.
earliest-
The consumer starts at the beginning of the partition. All retained messages are replayed from the oldest available offset.
none-
An exception is thrown if no previous offset is found. Use this to detect accidental group-name changes or offset expiry.
by_duration:<ISO-8601 duration>-
(Kafka 4.0+) The consumer starts at the first offset with a timestamp at or after
now - duration. For example,by_duration:PT1Hstarts one hour back andby_duration:P1Dstarts one day back. Like the other values, this only takes effect when the group has no committed offset.
-
Java
-
YAML
// New consumer group starting 1 hour back (only on first run)
from("kafka:orders?brokers=localhost:9092&groupId=reporting&autoOffsetReset=by_duration:PT1H")
.log("Order received: ${body}"); - route:
from:
uri: kafka:orders
parameters:
brokers: "localhost:9092"
groupId: reporting
autoOffsetReset: "by_duration:PT1H"
steps:
- log:
message: "Order received: ${body}" If you want to reposition an existing consumer group on every restart, use the seekTo option (BEGINNING or END) instead. Unlike autoOffsetReset, seekTo applies unconditionally on each consumer start, regardless of whether committed offsets exist. |
Pausable Consumers
The Kafka component supports pausable consumers. This type of consumer can pause consuming data based on conditions external to the component itself, such as an external system being unavailable or other transient conditions.
from("kafka:topic?groupId=my-group")
.pausable(new KafkaConsumerListener(), () -> canContinue())
.routeId("pausable-route")
.process(this::process)
.to("some:destination"); In this example, consuming messages can pause (by calling the Kafka’s Consumer pause method) if the result from canContinue is false.
The pausable EIP is meant to be used as a support mechanism when there is an exception somewhere in the route that prevents the exchange from being processed. More specifically, the check called by the pausable EIP should be used to test for transient conditions preventing the exchange from being processed. |
When using pausable consumers, it is recommended to set autoCommitEnable=false and allowManualCommit=true so that offsets are only committed after successful processing. With autoCommitEnable=true, Kafka may auto-commit offsets for records that were polled but not yet processed, which can lead to message loss during pause/resume cycles. |
| most users should prefer using the RoutePolicy, which offers better control of the route. |
Kafka Headers propagation
When consuming messages from Kafka, headers will be propagated to camel exchange headers automatically. Producing flow backed by same behaviour - camel headers of particular exchange will be propagated to kafka message headers.
Since kafka headers allow only byte[] values, in order camel exchange header to be propagated its value should be serialized to bytes[], otherwise header will be skipped. The following header value types are supported: String, Integer, Long, Double, Boolean, byte[]. Note: all headers propagated from kafka to camel exchange will contain byte[] value by default. To override default functionality, these uri parameters can be set: headerDeserializer for from route and headerSerializer for to route. For example:
-
Java
-
XML
-
YAML
from("kafka:my_topic?headerDeserializer=#myDeserializer")
.to("kafka:my_topic?headerSerializer=#mySerializer"); <route>
<from uri="kafka:my_topic?headerDeserializer=#myDeserializer"/>
<to uri="kafka:my_topic?headerSerializer=#mySerializer"/>
</route> - route:
from:
uri: kafka:my_topic
parameters:
headerDeserializer: "#myDeserializer"
steps:
- to:
uri: kafka:my_topic
parameters:
headerSerializer: "#mySerializer" By default, all headers are being filtered by KafkaHeaderFilterStrategy. Strategy filters out headers which start with Camel or org.apache.camel prefixes. Default strategy can be overridden by using headerFilterStrategy uri parameter in both to and from routes:
-
Java
-
XML
-
YAML
from("kafka:my_topic?headerFilterStrategy=#myStrategy")
.to("kafka:my_topic?headerFilterStrategy=#myStrategy"); <route>
<from uri="kafka:my_topic?headerFilterStrategy=#myStrategy"/>
<to uri="kafka:my_topic?headerFilterStrategy=#myStrategy"/>
</route> - route:
from:
uri: kafka:my_topic
parameters:
headerFilterStrategy: "#myStrategy"
steps:
- to:
uri: kafka:my_topic
parameters:
headerFilterStrategy: "#myStrategy" myStrategy object should be a subclass of HeaderFilterStrategy and must be placed in the Camel registry, either manually or by registration as a bean in Spring, as it is CamelContext aware.
Kafka Transaction
You need to add transactionalId=<tx-id> or transacted=true to enable Kafka transactions with the producer. The generated ID used by transacted=true is based on the endpoint and route IDs; it is not unique across replicas of the same application. For read-process-write exactly-once processing, configure an explicit transactionalId that is unique per producer instance and stable across restarts of that instance.
-
Java
-
XML
-
YAML
from("direct:transaction")
.to("kafka:my_topic?transacted=true"); <route>
<from uri="direct:transaction"/>
<to uri="kafka:my_topic?transacted=true"/>
</route> - route:
from:
uri: direct:transaction
steps:
- to:
uri: kafka:my_topic
parameters:
transacted: true At the end of exchange routing, the kafka producer would commit the transaction or abort it if there is an Exception throwing or the exchange is RollbackOnly. Since Kafka does not support transactions in multi threads, it will throw ProducerFencedException if there is another producer with the same transaction.id to make the transactional request.
It would work with JTA camel-jta by using transacted() and if it involves some resources (SQL or JMS), which supports XA, then they would work in tandem, where they both will either commit or rollback at the end of the exchange routing. In some cases, if the JTA transaction manager fails to commit (during the 2PC processing), but kafka transaction has been committed before and there is no chance to roll back the changes since the kafka transaction does not support JTA/XA spec. There is still a risk with the data consistency.
When you use the transacted=true parameter, the transactionalId is made from the endpoint ID and route ID. If you want finer control, set the transactionalId parameter; use a different ID for each producer endpoint. The old style of using additionalProperties[transactional.id] is still valid. For exactly-once read-process-write, the ID must be unique across application replicas and stable across restarts of the same producer instance; the generated endpoint/route ID alone does not meet that requirement.
If both transacted=true and transactionalId are present, the latter takes precedence.
Kafka exactly-once (read-process-write)
The Kafka component can atomically commit records produced by a route and the source consumer offsets. This is an opt-in feature for Kafka-to-Kafka routes. Configure exactlyOnce=true on both Kafka endpoints:
-
Source consumer:
exactlyOnce=true,allowManualCommit=true,autoCommitEnable=falseandbreakOnFirstError=true. Automatic commits are disabled. A transactional destination producer commits the source offsets with its output records; when a successful route branch does not use a Kafka producer (for example, a filter drops the record), Camel commits the source offset directly on the polling consumer thread. -
Destination producer:
exactlyOnce=trueand an explicittransactionalId(oradditionalProperties[transactional.id]).transacted=truealone is not sufficient in this mode. Treat the configuredtransactionalIdas a base ID: Camel appends the owning route ID when it creates the producer (<base>-<routeId>). This gives separate producer instances created for the same sink URI in different routes distinct Kafka transactional IDs. Configure an explicit, stablerouteIdfor each route, and choose a basetransactionalIdthat is unique to this Camel runtime instance and stable across restarts. The base ID must still differ across application replicas; the route suffix does not make two different Camel instances globally unique. If the same route creates multiple independent producer instances with the same base ID, configure distinct base IDs for those producers as well. -
Consumers reading the destination topic:
isolation.level=read_committed.
from("kafka:in?groupId=my-group&exactlyOnce=true&allowManualCommit=true&autoCommitEnable=false&breakOnFirstError=true")
.to("kafka:out?exactlyOnce=true&transactionalId={{orders.kafka.transactional-id}}"); The manual-commit token is used by Camel to capture source offset metadata; do not call its commit() method in this mode. The consumer group metadata is captured on the Kafka polling thread and retained in an exchange property, so removeHeaders("*") or replacing the message does not discard the source offsets. The producer sends the offsets to the transaction with sendOffsetsToTransaction immediately before commitTransaction. The metadata must belong to one consumer group generation; a rebalance before the transaction commits causes Kafka to reject the stale generation and the transaction is recovered as a failure. Kafka brokers must be version 2.5 or later to support the full ConsumerGroupMetadata fencing information.
The source endpoint must use an explicit, non-blank groupId, must not configure offsetRepository, and must use consumersCount=1. The built-in synchronous and asynchronous manual-commit factories are supported. A custom KafkaManualCommitFactory is not supported because Camel needs the record offset, leader epoch and poll-thread-captured group metadata. batching=true, consumersCount greater than one, seekTo, and a ResumeStrategy are rejected on the source: batching can span consumer group generations, while seek/resume policies can reposition the consumer past uncommitted records. Configure the source and destination endpoints against the same Kafka cluster; cross-cluster offset commits are not supported. Streaming mode currently runs one source record per transaction. For throughput, tune the Kafka producer’s batch.size and linger.ms options; do not enable consumer batching with exactly-once mode. To publish to several output topics in one transaction, use one exactly-once producer endpoint and set the CamelKafkaOverrideTopic header for each output record rather than routing to multiple Kafka producer endpoints.
breakOnFirstError=true is required so a failed record is replayed from the last committed offset. If the input topic is itself written transactionally, configure isolation.level=read_committed on the source consumer as well.
Exactly-once mode supports one Kafka source and one exactly-once producer transaction for the normal source route. A Kafka producer used by the normal route must set exactlyOnce=true; a non-transactional or ordinary transactional destination is rejected as a source-claim failure when the exchange is processed, not during route startup. This is not a Kafka send failure: even if an error handler consumes the rejection, the source transaction is aborted and the source record is replayed rather than skipped. A Kafka producer used as the destination of the selected failure handler is supported as a separate case. This includes a deadLetterChannel destination and an onException(…).handled(true) destination. Sends inside a doCatch body are local recovery and remain in the normal source-output transaction; they may use the source producer, including when it is the first Kafka producer to claim the source offsets. Sends after the doCatch block are also normal route sends. Sends made by an onException(…).continued(true) failure processor are classified as failure-handler deliveries. Sends in the original route after the continued(true) handler returns are normal route sends. If a source-output transaction is already open, a failure-handler Kafka destination, including one used by onException(…).continued(true), must use a separate producer; an exactly-once failure-handler destination must have a different transactionalId from the source-output producer. Split/wireTap child copies cannot claim source metadata: a split that sends from each child without aggregating back to the parent is rejected and the source record is replayed. A split or multicast can be used when it aggregates back to the original parent exchange and the Kafka destination is invoked only after aggregation completes. For example, the split children can be aggregated into a list and the parent exchange can publish each list item as a Kafka record in one transaction:
from("kafka:in?groupId=orders&exactlyOnce=true&allowManualCommit=true&autoCommitEnable=false&breakOnFirstError=true")
.split(body().tokenize(","), AggregationStrategies.groupedBody())
.transform(body().append("!"))
.end()
.to("kafka:out?exactlyOnce=true&transactionalId=orders-out"); Do not place an asynchronous hand-off between the Kafka source and the exactly-once producer. The component tracks sends made by the original source exchange to the following asynchronous endpoint schemes: seda, vm, disruptor, disruptor-vm, and reactive-streams, but marks a hand-off only when the target route can reach Kafka. If one of these endpoints is reached before an exactly-once Kafka producer claims the source offsets and its target route can reach Kafka, the source record is replayed instead of committing its offset directly. A statically non-Kafka target, such as a SEDA route to a local audit processor, does not mark the source exchange and does not by itself prevent an offset-only commit. Unresolved direct or asynchronous targets, Kamelet targets, and target route graphs containing RecipientList, RoutingSlip, DynamicRouter, or toD are conservatively treated as potentially Kafka-directed. A filtered record handed to one of these targets is replayed rather than directly committed, because Camel cannot prove that the target avoids Kafka. The hand-off marker is stored on the shared source metadata, so a copied exchange cannot hide a Kafka-directed hand-off from the original source exchange. Dynamic EIPs in the source route are not rejected merely because they appear in the route; the component records the endpoint actually reached by the exchange.
The event notifier is registered at CamelContext scope while at least one exactly-once source consumer is active. Registration is reference-counted and removed when the final such consumer stops. Because Camel dispatches sending events at context scope, sends on unrelated routes still incur per-send event-notification dispatch overhead. The notifier returns immediately for exchanges without exactly-once Kafka metadata, avoiding endpoint URI inspection and Kafka-specific hand-off bookkeeping for those exchanges, but it cannot avoid the underlying event dispatch.
A wireTap that can reach a Kafka producer is not supported for exactly-once sources. A WireTap runs on a copied exchange and cannot join the source producer transaction. The component validates WireTap targets before source polling begins, follows direct and asynchronous route endpoints (including sub-routes reached from the source route), and rejects targets that can reach Kafka. RecipientList, RoutingSlip, DynamicRouter, toD, and dynamic WireTap URIs inside a WireTap target are rejected conservatively because their destinations cannot be established safely at startup. Kamelet targets and unresolved direct or asynchronous targets are also treated as potentially Kafka-directed rather than assumed safe. A WireTap whose complete, resolvable target graph is statically non-Kafka is allowed. Use a synchronous Kafka destination on the original source exchange instead. Only one exactly-once transaction may be active on a destination producer at a time; serialize processing before a shared producer. The feature does not make unrelated external resources transactional.
A Kafka send failure is not retried inside the already-open exactly-once unit of work. If Camel’s error handler attempts redelivery before that transaction completes, the destination producer rejects the retry and marks the exchange rollback-only. The whole output transaction is aborted. Without a handler that completes the failure, breakOnFirstError=true replays the source record in a new unit of work and transaction. This avoids restarting the transaction in place: Camel resumes at the failed route step, which would otherwise discard output from earlier route steps without replaying those steps. maximumRedeliveries may cause Camel to invoke the failed route step again, but each in-transaction retry is rejected; the Kafka send is not retried in a fresh transaction. After those rejected attempts, a failure handler such as a deadLetterChannel or an onException(…).handled(true) clause can handle the original failure. When a supported non-Kafka failure-handler delivery succeeds, Camel skips the source record using the offset-only transaction described below. With maximumRedeliveries(2), for example, the first retry is rejected, which marks the exchange rollback-only and ends the redeliveries, and the failure-handler destination is invoked once; there is no new Kafka send attempt.
Any later send through the source producer in that transaction is rejected the same way, also one that is not a redelivery, such as a second send in a loop or in another doTry block. When a doCatch catches such a rejected send, in the route of the send or in a route that called it from a doTry (for example with direct), the failure is handled too, and Camel skips the source record using the offset-only transaction. To replay the record instead, throw the exception again in the doCatch block, or end it with rollback(): markRollbackOnly() is not told apart from the rejected send.
When a Kafka send failure, or another route failure, is handled successfully while the source-output transaction is already open, Camel aborts the source-output transaction and commits only the source offsets in a new transaction. This intentionally skips the source record only after the failure-handler delivery completes successfully. A Kafka destination invoked by the selected failure handler, including an onException(…).handled(true) output, is supported: a non-transactional Kafka producer must complete its send successfully, or an exactly-once Kafka producer must commit its own transaction, before the source offset-only transaction can commit. If the source-output producer is already active, the failure-handler Kafka destination must use a different producer transaction; an exactly-once failure-handler destination must have a different transactionalId from the source-output producer. Reusing the source producer would put the failure-handler record in the transaction that is aborted.
If a Kafka failure-handler destination is the first exactly-once producer to claim the source offsets (no source-output producer has started yet), its transaction commits the failure-handler record and source offsets together. If a non-transactional Kafka failure-handler destination is used before any source producer transaction has started, the source offset is committed directly only after the failure-handler send succeeds. A failed Kafka failure-handler send or failed failure-handler transaction is always treated as a failure that requires source replay, even when the selected failure handler handles its own delivery exception. With a deadLetterChannel, consider setting deadLetterHandleNewException=false so a failure while delivering to the DLQ is propagated rather than handled by the DLC’s default behavior.
When a Kafka failure-handler destination is a secondary send after the source-output transaction has started, the failure-handler Kafka delivery and the source offset-only commit are separate transactions, not one atomic transaction. If the failure-handler delivery succeeds but the source offset-only transaction cannot commit (for example, because of a rebalance, broker failure, or process crash), the source record is replayed and the failure handler may run again. Use an idempotent DLQ consumer or deduplication key when duplicate dead-letter deliveries are not acceptable.
Setting Kerberos config file
Configure the 'krb5.conf' file directly through the API:
static {
KafkaComponent.setKerberosConfigLocation("path/to/config/file");
} Alternatively, you can set the JVM system property:
java.security.krb5.conf=/path/to/config/file Authentication to Kafka
Kafka supports several ways to authenticate the clients to the server, including plain text, PKI (certificates) over TLS, you can refer to the Kafka documentation for a detailed view of the supported mechanisms. The kafka authentication and authorization is based on JAAS, so you must use a JAAS Login Module implementation on the client side.
Simplified Authentication Configuration
Instead of manually constructing JAAS configuration strings, you can use the saslAuthType option along with dedicated credential properties. This approach automatically derives the correct securityProtocol, saslMechanism, and saslJaasConfig values based on the selected authentication type.
The following authentication types are supported:
| saslAuthType | Description |
|---|---|
| No authentication (insecure, for development only) |
| SASL/PLAIN with username and password |
| SASL/SCRAM-SHA-256 authentication |
| SASL/SCRAM-SHA-512 authentication |
| SSL/TLS with client certificates (mTLS) |
| OAuth 2.0 / OIDC authentication |
| AWS MSK IAM authentication |
| Kerberos/GSSAPI authentication |
SCRAM Authentication Example
-
Java
-
XML
-
YAML
from("kafka:my-topic?brokers=localhost:9092&saslAuthType=SCRAM_SHA_512&saslUsername=myuser&saslPassword=mypassword")
.to("log:received"); <route>
<from uri="kafka:my-topic?brokers=localhost:9092&saslAuthType=SCRAM_SHA_512&saslUsername=myuser&saslPassword=mypassword"/>
<to uri="log:received"/>
</route> - route:
from:
uri: kafka:my-topic
parameters:
brokers: "localhost:9092"
saslAuthType: SCRAM_SHA_512
saslUsername: myuser
saslPassword: mypassword
steps:
- to:
uri: log:received Or using Spring Boot configuration:
camel.component.kafka.sasl-auth-type=SCRAM_SHA_512
camel.component.kafka.sasl-username=myuser
camel.component.kafka.sasl-password=mypassword OAuth Authentication Example
-
Java
-
XML
-
YAML
from("kafka:my-topic?brokers=localhost:9092&saslAuthType=OAUTH&oauthClientId=my-client&oauthClientSecret=my-secret&oauthTokenEndpointUri=https://auth.example.com/oauth/token")
.to("log:received"); <route>
<from uri="kafka:my-topic?brokers=localhost:9092&saslAuthType=OAUTH&oauthClientId=my-client&oauthClientSecret=my-secret&oauthTokenEndpointUri=https://auth.example.com/oauth/token"/>
<to uri="log:received"/>
</route> - route:
from:
uri: kafka:my-topic
parameters:
brokers: "localhost:9092"
saslAuthType: OAUTH
oauthClientId: my-client
oauthClientSecret: my-secret
oauthTokenEndpointUri: "https://auth.example.com/oauth/token"
steps:
- to:
uri: log:received Since Kafka 4.0, the client only calls an OAuth token endpoint that is listed in the JVM system property org.apache.kafka.sasl.oauthbearer.allowed.urls (a comma-separated list of URLs). Without it, the producer or consumer fails to start with The URL cannot be accessed due to restrictions. Update the system property 'org.apache.kafka.sasl.oauthbearer.allowed.urls' to allow the URL to be accessed. Set it to the oauthTokenEndpointUri, for example with -Dorg.apache.kafka.sasl.oauthbearer.allowed.urls=https://auth.example.com/oauth/token, or with Camel JBang camel run --jvm-args=-Dorg.apache.kafka.sasl.oauthbearer.allowed.urls=https://auth.example.com/oauth/token. |
AWS MSK IAM Authentication
When using AWS MSK with IAM authentication, ensure the aws-msk-iam-auth library is on the classpath:
-
Java
-
XML
-
YAML
from("kafka:my-topic?brokers=b-1.mycluster.kafka.us-east-1.amazonaws.com:9098&saslAuthType=AWS_MSK_IAM")
.to("log:received"); <route>
<from uri="kafka:my-topic?brokers=b-1.mycluster.kafka.us-east-1.amazonaws.com:9098&saslAuthType=AWS_MSK_IAM"/>
<to uri="log:received"/>
</route> - route:
from:
uri: kafka:my-topic
parameters:
brokers: "b-1.mycluster.kafka.us-east-1.amazonaws.com:9098"
saslAuthType: AWS_MSK_IAM
steps:
- to:
uri: log:received The simplified configuration is optional. If you need more control or are using a custom JAAS login module, you can still use the traditional approach with explicit securityProtocol, saslMechanism, and saslJaasConfig properties as shown below.
Traditional JAAS Configuration
This section will outline the main points for the authentication using Strimzi JAAS Login Module and plain text. The Strimzi OAuth contains several properties to fine tune, the authentication mechanism, so you can set them into the OAuthBearerLoginModule section.
The most basic way to authenticate is using the plain text login module with username and password. Beware that this is unsafe and and we suggest the OAuth over TLS for a fully secure mechanism.
Username and Password over TLS
camel.component.kafka.security-protocol = SASL_SSL
camel.component.kafka.sasl-mechanism=PLAIN
camel.component.kafka.sasl-jaas-config=org.apache.kafka.common.security.plain.PlainLoginModule required \
username="my_username" \
password="my_password"; There is the Strimzi OAuth Login Module that supports the more secure OAuth mechanisms, where you can set a refresh token, username/password and client secret. You must understand the Kafka Broker security settings to adequately configure the client security configuration.
OAuth Bearer Token with client secret
camel.component.kafka.security-protocol = SASL_PLAINTEXT
camel.component.kafka.sasl-mechanism = OAUTHBEARER
camel.component.kafka.sasl-jaas-config = org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required \
oauth.client.id="kafka-producer-client" \
oauth.client.secret="kafka-producer-client-secret" \
oauth.username.claim="preferred_username" \
oauth.ssl.truststore.location="docker/certificates/ca-truststore.p12" \
oauth.ssl.truststore.type="pkcs12" \
oauth.ssl.truststore.password="changeit" \
oauth.token.endpoint.uri="https://keycloak:8443/realms/demo/protocol/openid-connect/token" ;
camel.component.kafka.additional-properties[sasl.login.callback.handler.class]=io.strimzi.kafka.oauth.client.JaasClientOauthLoginCallbackHandler OAuth Bearer Token with refresh token
camel.component.kafka.security-protocol = SASL_PLAINTEXT
camel.component.kafka.sasl-mechanism = OAUTHBEARER
camel.component.kafka.sasl-jaas-config = org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required \
oauth.client.id="kafka-producer-client" \
oauth.refresh.token="my_refresh_token"
oauth.username.claim="preferred_username" \
oauth.ssl.truststore.location="docker/certificates/ca-truststore.p12" \
oauth.ssl.truststore.type="pkcs12" \
oauth.ssl.truststore.password="changeit" \
oauth.token.endpoint.uri="https://keycloak:8443/realms/demo/protocol/openid-connect/token" ;
camel.component.kafka.additional-properties[sasl.login.callback.handler.class]=io.strimzi.kafka.oauth.client.JaasClientOauthLoginCallbackHandler Schema registry
A schema registry stores the schemas (Avro, JSON Schema or Protobuf) of the records in a topic, and the serializer and deserializer of the registry vendor write and read the records with them. The schemaRegistryVendor and schemaFormat options set up the value serializer (producer), the value deserializer (consumer) and the registry properties of the vendor, so that you do not need to know the class names or the property names of the vendor. The schemaRegistryURL option is set as the registry URL of the vendor.
| schemaRegistryVendor | schemaFormat | What Camel sets |
|---|---|---|
|
| The |
|
| The |
|
| The |
|
| The |
The schemaFormat is avro by default. A format that the vendor does not support fails when the producer or consumer starts: azure with json or protobuf, and apicurio with json when com.networknt:json-schema-validator 3.x is on the classpath (see the note in the Apicurio section). The specificAvroReader option is set under the property of the vendor.
What you set yourself takes precedence: a valueSerializer or valueDeserializer other than the default, and any additionalProperties, such as a property of the vendor that Camel also sets. A valueSerializer or valueDeserializer set to the default (StringSerializer or StringDeserializer) cannot be told apart from the default, so the vendor replaces it. When the vendor is set on the component, and one endpoint must send or receive plain strings, such as a dead letter topic, set an empty schemaRegistryVendor on that endpoint, for example kafka:dlq?schemaRegistryVendor=. The producer converts the message body for the value serializer that the Kafka producer gets, also when it is set with the value.serializer additional property. The key serializer and deserializer are not changed: the keys stay strings unless you set keySerializer and keyDeserializer. Leave schemaRegistryVendor unset to configure the serializer, deserializer and registry properties yourself, as before.
The body of the message to send must be a value that the serializer of the vendor accepts, such as an Avro GenericRecord or a class generated from the Avro schema.
Camel does not include the serde libraries of the vendors: add the serde jar of the vendor and format to your application (Camel JBang downloads it, see below). The Confluent serde jars are not in Maven Central: add the Confluent Maven repository https://packages.confluent.io/maven/, or have the jars in a repository of your own. |
| schemaRegistryVendor | Serde jars (Maven groupId:artifactId) |
|---|---|
|
|
|
|
|
|
|
|
For example with Maven, for Confluent and Avro:
<repositories>
<repository>
<id>confluent</id>
<url>https://packages.confluent.io/maven/</url>
</repository>
</repositories>
<dependency>
<groupId>io.confluent</groupId>
<artifactId>kafka-avro-serializer</artifactId>
<version>8.4.1</version>
</dependency> Camel JBang downloads the serde jar of the vendor and format when the producer or consumer starts, so you do not add it with --dep. The Confluent serde jars are not in Maven Central, so add the Confluent Maven repository with --repos=confluent (Camel JBang knows the confluent repository by name):
camel run MyRoute.java --repos=confluent When the serializer or deserializer of the vendor cannot be loaded (the jar is not on the classpath, or Camel JBang cannot download it, such as a Confluent jar without --repos=confluent), the producer or consumer fails to start with a message that names the Maven artifact to add.
Confluent Schema Registry
Supports Avro, JSON Schema and Protobuf. The serde jars are only in the Confluent Maven repository, not in Maven Central. The Avro serde and the registry client are licensed under the Apache License 2.0; the JSON Schema and Protobuf serdes are also listed under the Confluent Community License, so check their license for your use. Registries that implement the Confluent registry API, such as Karapace and Redpanda, work with confluent too. |
-
Java
-
YAML
from("kafka:orders?brokers=localhost:9092&schemaRegistryVendor=confluent&schemaRegistryURL=http://localhost:8081")
.log("Received ${body}"); - route:
from:
uri: kafka:orders
parameters:
brokers: "localhost:9092"
schemaRegistryVendor: confluent
schemaRegistryURL: "http://localhost:8081"
steps:
- log: "Received ${body}" Apicurio Registry
Supports Avro, JSON Schema and Protobuf, with the serdes of Apicurio Registry 3.x. The 2.x serdes have other artifact names and property names, and are not set up by apicurio. JSON Schema (schemaFormat=json) fails at startup when com.networknt:json-schema-validator 3.x is on the classpath: the Apicurio JSON Schema serde (io.apicurio:apicurio-registry-jsonschema-serde-kafka 3.x) depends on com.networknt:json-schema-validator 1.5.x, while for example camel-yaml-dsl-validator, camel-json-validator and Camel JBang use com.networknt:json-schema-validator 3.x (upgraded for Jackson 3 in CAMEL-23172). In 3.x, SchemaLoader changed from an interface to a class, so the 1.5.x classes of the serde fail to link against the 3.x classes already loaded, with an IncompatibleClassChangeError. Use schemaFormat=avro or schemaFormat=protobuf with apicurio, or use schemaRegistryVendor=confluent with schemaFormat=json (the Confluent compatible API of Apicurio Registry works with confluent). |
The URL is the URL of the registry API of Apicurio Registry 3.x, which ends with /apis/registry/v3.
-
Java
-
YAML
from("kafka:orders?brokers=localhost:9092&schemaRegistryVendor=apicurio&schemaFormat=protobuf"
+ "&schemaRegistryURL=http://localhost:8080/apis/registry/v3")
.log("Received ${body}"); - route:
from:
uri: kafka:orders
parameters:
brokers: "localhost:9092"
schemaRegistryVendor: apicurio
schemaFormat: protobuf
schemaRegistryURL: "http://localhost:8080/apis/registry/v3"
steps:
- log: "Received ${body}" AWS Glue Schema Registry
Supports Avro, JSON Schema and Protobuf, through one serializer and deserializer whose dataFormat Camel sets from schemaFormat. There is no local emulator of AWS Glue: test against AWS. |
AWS Glue is addressed by the AWS region and the name of the registry, not by a URL. The region is taken from the AWS default region provider chain (such as the AWS_REGION environment variable), or set with the region additional property. The registry is default-registry unless you set the registry.name additional property. The AWS credentials are taken from the AWS default credentials provider chain.
-
Java
-
YAML
from("kafka:orders?brokers=localhost:9092&schemaRegistryVendor=aws-glue&schemaFormat=json"
+ "&additionalProperties.region=eu-west-1&additionalProperties.registry.name=my-registry")
.log("Received ${body}"); - route:
from:
uri: kafka:orders
parameters:
brokers: "localhost:9092"
schemaRegistryVendor: aws-glue
schemaFormat: json
additionalProperties.region: eu-west-1
additionalProperties.registry.name: my-registry
steps:
- log: "Received ${body}" Azure Schema Registry
Supports Avro only. Azure has no released JSON Schema serde (only a beta) and no Protobuf serde, so azure with json or protobuf fails when the producer or consumer starts. |
The schemaRegistryURL is the fully qualified namespace of the Event Hubs namespace, such as my-namespace.servicebus.windows.net. A producer needs the schema group, which you set with the schema.group additional property. Camel sets use.azure.credential=true, so that the serde authenticates with the DefaultAzureCredential of the Azure Identity library (environment variables, managed identity, Azure CLI and so on). To use another credential, bind a com.azure.core.credential.TokenCredential bean and set it as the schema.registry.credential additional property, which takes precedence. The Azure serde reads auto.register.schemas, use.azure.credential and specific.avro.reader as Boolean: when you set them as additional properties, such as additionalProperties.auto.register.schemas=false to turn off the registration of schemas, Camel converts the true or false string to a Boolean.
The dependencies of azure-schemaregistry-kafka-avro ask for different versions of com.azure:azure-core, and Maven picks the older one, which lacks TokenRequestContext.isCaeEnabled() that Azure Identity calls: the first send then fails with a NoSuchMethodError. Add a recent com.azure:azure-core next to the serde, or import the com.azure:azure-sdk-bom. Camel JBang downloads the com.azure:azure-core of the Azure SDK BOM together with the serde. The options to connect to Event Hubs with the Kafka protocol are left out of the example.
-
Java
-
YAML
from("direct:orders")
.to("kafka:orders?brokers=my-namespace.servicebus.windows.net:9093"
+ "&schemaRegistryVendor=azure&schemaRegistryURL=my-namespace.servicebus.windows.net"
+ "&additionalProperties.schema.group=my-group"
+ "&additionalProperties.schema.registry.credential=#bean:myCredential"); - route:
from:
uri: direct:orders
steps:
- to:
uri: kafka:orders
parameters:
brokers: "my-namespace.servicebus.windows.net:9093"
schemaRegistryVendor: azure
schemaRegistryURL: my-namespace.servicebus.windows.net
additionalProperties.schema.group: my-group
additionalProperties.schema.registry.credential: "#bean:myCredential" Logging in to the schema registry
A registry that requires a login is reached with the login of its vendor:
| schemaRegistryVendor | How it logs in |
|---|---|
| Basic auth with |
| Basic auth with |
| The AWS default credentials provider chain: the |
| The |
schemaRegistryPassword and schemaRegistryOauthClientSecret are secret options, which Camel masks in logs. In an endpoint URI, give a secret that has characters such as & or + in RAW(), or set it from a property placeholder or a vault. What you set in additionalProperties, such as basic.auth.credentials.source=SASL_INHERIT to use the SASL login of the Kafka connection, takes precedence. With OAuth2 and confluent, the Confluent client checks schemaRegistryOauthTokenEndpoint against the JVM system property org.apache.kafka.sasl.oauthbearer.allowed.urls, just as the Kafka client does for the SASL OAuth login. List the token endpoint in this property, or the producer or consumer fails to start with The URL cannot be accessed due to restrictions.
For example, Confluent Cloud with the API key of its Schema Registry:
-
Java
-
YAML
from("kafka:orders?schemaRegistryVendor=confluent&schemaRegistryURL=https://psrc-123.eu-central-1.aws.confluent.cloud"
+ "&schemaRegistryUsername={{registry.key}}&schemaRegistryPassword=RAW({{registry.secret}})")
.log("Received ${body}"); - route:
from:
uri: kafka:orders
parameters:
schemaRegistryVendor: confluent
schemaRegistryURL: https://psrc-123.eu-central-1.aws.confluent.cloud
schemaRegistryUsername: "{{registry.key}}"
schemaRegistryPassword: "RAW({{registry.secret}})"
steps:
- log: "Received ${body}" And Apicurio Registry with a Keycloak client:
- route:
from:
uri: kafka:orders
parameters:
schemaRegistryVendor: apicurio
schemaRegistryURL: http://registry:8080/apis/registry/v3
schemaRegistryOauthTokenEndpoint: http://keycloak:8080/realms/registry/protocol/openid-connect/token
schemaRegistryOauthClientId: orders-consumer
schemaRegistryOauthClientSecret: "RAW({{registry.client.secret}})"
steps:
- log: "Received ${body}" Batching Consumer
To use a Kafka batching consumer with Camel, an application has to set the configuration batching to true.
The received records are stored in a list in the exchange used in the pipeline. As such, it is possible to commit individually every record or the whole batch at once by committing the last exchange on the list.
The size of the batch is controlled by the option maxPollRecords.
Camel will wait until the number of records has been received per batch size (maxPollRecords). However, this can take a long time, if there are too few records and no new records is being received.
To avoid blocking for too long, waiting for the whole set of records to fill the batch, it is possible to use the pollTimeoutMs option to set a timeout for the polling. The timeout is only triggered if there has not received any new messages for the given timeout period. So for example if pollTimeoutMs=10000 then the timeout is 10 seconds, and this will only trigger if Camel did not receive any new messages from Kafka for 10 seconds. The timeout trigger will reset if a message has been received, so if you continuously and slowly receive new messages, then this timeout may not trigger for a long time. Therefore, the option batchingIntervalMs can therefore be used to specify an interval (in mills) to trigger the batch completion, to avoid waiting for more messages to be received to reach the batch size. For example setting batchingIntervalMs=20000 would let Camel wait at most pollTimeoutMs + batchingIntervalMs before triggering a batch completion. In this example that would be 30 seconds.
Notice the pollTimeoutMs should not be set to a high value, as it’s used directly by Kafka while receiving new messages from the broker. Camel is not active during this processing, and if the option has been configured with a high value, then Camel cannot trigger batch timeout or interval completion ahead of time. Therefore, it’s recommended to keep this value as default.
Batch Headers
The exchange carrying the batch also exposes the record metadata headers that every record in the batch agrees on: CamelKafkaTopic and CamelKafkaPartition. This makes it possible to read them on the batch itself, before splitting it. When the batch is split, each child exchange carries the body and the headers of its own record:
from("kafka:topic?groupId=myGroup&batching=true&maxPollRecords=10")
.log("Received a batch of ${body.size} records from ${header.CamelKafkaTopic}")
.split(body())
.log("Record ${body} at offset ${header.CamelKafkaOffset}")
.end(); A header is only set on the batch when every record in the batch carries the same value for it. If the batch spans multiple topics or partitions, the corresponding header is not set, since no single value would be correct for the batch as a whole. Per-record headers that naturally differ, such as CamelKafkaOffset, are never set on the batch — read those from the individual exchanges in the body.
Automatic Commits
By default, Camel uses automatic commits when using batch processing. In this case, Camel automatically commits the records after they have been successfully processed by the application.
In case of failures, the records will not be processed.
The code below provides an example of this approach:
from("kafka:topic?groupId=myGroup&pollTimeoutMs=1000&batching=true&maxPollRecords=10&autoOffsetReset=earliest")
.process(e -> {
final List<?> exchanges = e.getMessage().getBody(List.class);
if (exchanges == null || exchanges.isEmpty()) {
return;
}
for (Object obj : exchanges) {
if (obj instanceof Exchange exchange) {
LOG.info("Processing exchange with body {}", exchange.getMessage().getBody(String.class));
}
}
})
.to("mock:result"); Handling Errors with Automatic Commits
When using automatic commits, Camel will not commit records if there is a failure in processing. Because of this, there is a risk that records could be reprocessed multiple times.
It is recommended to implement appropriate error handling mechanisms and patterns (i.e.; such as dead-letter queues), to prevent failed records from blocking processing progress.
The code below provides an example of handling errors with automatic commits:
onException(IllegalArgumentException.class).process(exchange -> {
LOG.warn("Failed to process batch {}", exchange.getMessage().getBody());
LOG.warn("Failed to process due to {}", exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Throwable.class).getMessage());
}).continued(true);
from("kafka:topic?groupId=myGroup&pollTimeoutMs=1000&batching=true&maxPollRecords=10&autoOffsetReset=earliest")
.process(e -> {
final List<?> exchanges = e.getMessage().getBody(List.class);
if (exchanges == null || exchanges.isEmpty()) {
return;
}
for (Object o : exchanges) {
if (o instanceof Exchange exchange) {
LOG.info("Processing exchange with body {}", exchange.getMessage().getBody(String.class));
}
}
})
.to("mock:result"); | In a production scenario, applications should send failed records to a separate topic (dead-letter queue) or fix the condition that led to the failure. |
Break on First Error in Batching Mode
The breakOnFirstError option is also supported in batching mode, providing the same error handling behavior as in streaming mode but applied to batch processing.
When breakOnFirstError=true is configured with batching enabled:
-
Auto Commit Mode: When an error occurs during batch processing, Camel will commit the current batch position and trigger a consumer reconnection. This allows the problematic batch to be retried on the next polling cycle.
-
Manual Commit Mode: When an error occurs, the route’s error handler is responsible for performing the manual commit (if desired) before the consumer reconnects.
-
Reconnection: After an error triggers
breakOnFirstError, the consumer automatically reconnects and resumes polling from the committed position.
The behavior is consistent with streaming mode, ensuring that error handling patterns work similarly across both processing modes.
Example with automatic commits:
-
Java DSL
-
YAML
-
Processor Implementation
from("kafka:topic?groupId=myGroup&pollTimeoutMs=1000&batching=true&maxPollRecords=10&breakOnFirstError=true&autoCommitEnable=true")
.process(e -> {
final List<?> exchanges = e.getMessage().getBody(List.class);
// Process batch - any exception will trigger breakOnFirstError behavior
for (Object exchange : exchanges) {
// ... processing logic
}
}).to("mock:result"); - route:
from:
uri: kafka:topic
parameters:
groupId: myGroup
pollTimeoutMs: 1000
batching: true
maxPollRecords: 10
breakOnFirstError: true
autoCommitEnable: true
steps:
- process:
ref: batchProcessor
- to:
uri: mock:result @Component("batchProcessor")
public class BatchProcessor implements Processor {
private static final Logger LOG = LoggerFactory.getLogger(BatchProcessor.class);
@Override
public void process(Exchange exchange) throws Exception {
final List<?> exchanges = exchange.getMessage().getBody(List.class);
if (exchanges == null || exchanges.isEmpty()) {
return;
}
// Process each exchange in the batch
for (Object obj : exchanges) {
if (obj instanceof Exchange batchExchange) {
String body = batchExchange.getMessage().getBody(String.class);
LOG.info("Processing exchange with body: {}", body);
// Your business logic here
// Any exception thrown will trigger breakOnFirstError behavior
processMessage(body);
}
}
}
private void processMessage(String message) {
// Implement your message processing logic
// Throw exceptions for error conditions that should trigger breakOnFirstError
if (message.contains("error")) {
throw new RuntimeException("Processing failed for message: " + message);
}
}
} Example with manual commits:
-
Java DSL
-
YAML
-
Processor Implementations
// Error handler that performs manual commit before reconnection
onException(Exception.class)
.handled(false)
.process(exchange -> {
// Commit manually when error occurs
KafkaManualCommit manual = exchange.getMessage()
.getHeader("CamelKafkaManualCommit", KafkaManualCommit.class);
manual.commit();
});
from("kafka:topic?groupId=myGroup&batching=true&breakOnFirstError=true&autoCommitEnable=false&allowManualCommit=true")
.process(e -> {
final List<?> exchanges = e.getMessage().getBody(List.class);
// Process batch - errors will be handled by the error handler above
for (Object exchange : exchanges) {
// ... processing logic
}
})
.process(exchange -> {
// Manual commit on successful processing
KafkaManualCommit manual = exchange.getMessage()
.getHeader("CamelKafkaManualCommit", KafkaManualCommit.class);
manual.commit();
})
.to("mock:result"); - onException:
exception:
- java.lang.Exception
handled:
constant:
expression: "false"
steps:
- process:
ref: errorCommitProcessor
- route:
from:
uri: kafka:topic
parameters:
groupId: myGroup
batching: true
breakOnFirstError: true
autoCommitEnable: false
allowManualCommit: true
steps:
- process:
ref: batchProcessorManual
- process:
ref: successCommitProcessor
- to:
uri: mock:result @Component("batchProcessorManual")
public class BatchProcessorManual implements Processor {
private static final Logger LOG = LoggerFactory.getLogger(BatchProcessorManual.class);
@Override
public void process(Exchange exchange) throws Exception {
final List<?> exchanges = exchange.getMessage().getBody(List.class);
if (exchanges == null || exchanges.isEmpty()) {
return;
}
// Process each exchange in the batch
for (Object obj : exchanges) {
if (obj instanceof Exchange batchExchange) {
String body = batchExchange.getMessage().getBody(String.class);
LOG.info("Processing exchange with body: {}", body);
// Your business logic here
// Errors will be handled by the error handler
processMessage(body);
}
}
}
private void processMessage(String message) {
// Implement your message processing logic
if (message.contains("error")) {
throw new RuntimeException("Processing failed for message: " + message);
}
}
}
@Component("errorCommitProcessor")
public class ErrorCommitProcessor implements Processor {
private static final Logger LOG = LoggerFactory.getLogger(ErrorCommitProcessor.class);
@Override
public void process(Exchange exchange) throws Exception {
LOG.warn("Error occurred, performing manual commit before reconnection");
KafkaManualCommit manual = exchange.getMessage()
.getHeader("CamelKafkaManualCommit", KafkaManualCommit.class);
if (manual != null) {
manual.commit();
LOG.info("Manual commit completed after error");
}
}
}
@Component("successCommitProcessor")
public class SuccessCommitProcessor implements Processor {
private static final Logger LOG = LoggerFactory.getLogger(SuccessCommitProcessor.class);
@Override
public void process(Exchange exchange) throws Exception {
LOG.debug("Batch processed successfully, performing manual commit");
KafkaManualCommit manual = exchange.getMessage()
.getHeader("CamelKafkaManualCommit", KafkaManualCommit.class);
if (manual != null) {
manual.commit();
LOG.debug("Manual commit completed after successful processing");
}
}
} Manual Commits
When working with batch processing with manual commits, it’s up to the application to commit the records, and handle the outcome of potentially invalid records.
The code below provides an example of this approach:
from("kafka:topic?batching=true&allowManualCommit=true&maxPollRecords=100&kafkaManualCommitFactory=#class:org.apache.camel.component.kafka.consumer.DefaultKafkaManualCommitFactory")
.process(e -> {
final List<?> exchanges = e.getMessage().getBody(List.class);
if (exchanges == null || exchanges.isEmpty()) {
return;
}
// Use the last exchange in the list to commit the whole batch
final Object tmp = exchanges.getLast();
if (tmp instanceof Exchange exchange) {
KafkaManualCommit manual =
exchange.getMessage().getHeader("CamelKafkaManualCommit", KafkaManualCommit.class);
LOG.debug("Performing manual commit");
manual.commit();
LOG.debug("Done performing manual commit");
}
}); Dealing with long polling timeouts
In some cases, applications may want the polling process to have a long timeout (see: pollTimeoutMs).
To properly do so, first make sure to have a max polling interval that is higher than the polling timeout (see: maxPollIntervalMs).
Then, increase the shutdown timeout to ensure that committing, closing and other Kafka operations are not abruptly aborted. For instance:
getCamelContext().getShutdownStrategy().setTimeout(10000); Or using configuration properties:
camel.main.shutdown-timeout=10000 Custom Subscription Adapters
Applications with complex subscription logic may provide a custom bean to handle the subscription process. To so, it is necessary to implement the interface SubscribeAdapter.
public class CustomSubscribeAdapter implements SubscribeAdapter {
@Override
public void subscribe(Consumer<?, ?> consumer, ConsumerRebalanceListener reBalanceListener, TopicInfo topicInfo) {
if (topicInfo.isPattern()) {
consumer.subscribe(topicInfo.getPattern(), reBalanceListener);
} else {
consumer.subscribe(topicInfo.getTopics(), reBalanceListener);
}
}
} Then, it is necessary to add it as a named bean instance to the registry:
context.getRegistry().bind("subscribeAdapter", new CustomSubscribeAdapter()); Interoperability
JMS
When interoperating Kafka and JMS, it may be necessary to coerce the JMS headers into their expected type.
For instance, when consuming messages from Kafka carrying JMS headers and then sending them to a JMS broker, those headers are first deserialized into a byte array. Then, the camel-jms component tries to coerce this byte array into the specific type used by. However, both the origin endpoint as well as how this was setup on the code itself may affect how the data is serialized and deserialized. As such, it is not feasible to naively assume the data type of the byte array.
To address this issue, we provide a custom header deserializer to force Kafka to de-serialize the JMS data according to the JMS specification. This approach ensures that the headers are properly interpreted and processed by the camel-jms component.
Due to the inherent complexity of each possible system and endpoint, it may not be possible for this deserializer to cover all possible scenarios. As such, it is provided as model that can be modified and/or adapted for the specific needs of each application.
To utilize this solution, you need to modify the route URI on the consumer end of the pipeline by including the headerDeserializer option. For example:
-
Java
-
XML
-
YAML
from("kafka:topic?headerDeserializer=#class:org.apache.camel.component.kafka.consumer.support.interop.JMSDeserializer")
.to("direct:process"); <route>
<from uri="kafka:topic?headerDeserializer=#class:org.apache.camel.component.kafka.consumer.support.interop.JMSDeserializer"/>
<to uri="direct:process"/>
</route> - route:
from:
uri: kafka:topic
parameters:
headerDeserializer: "#class:org.apache.camel.component.kafka.consumer.support.interop.JMSDeserializer"
steps:
- to:
uri: direct:process Producer Performance
If the producer is performing too slowly for your needs, you may want to aggregate the exchanges before sending.
-
Java
-
XML
-
YAML
from("direct:start")
.aggregate(constant(true), new GroupedExchangeAggregationStrategy())
.completionSize(100)
.completionTimeout(1000)
.to("kafka:my-topic"); <route>
<from uri="direct:start"/>
<aggregate aggregationStrategy="#groupedExchange" completionSize="100" completionTimeout="1000">
<correlationExpression>
<constant>true</constant>
</correlationExpression>
<to uri="kafka:my-topic"/>
</aggregate>
</route> - route:
from:
uri: direct:start
steps:
- aggregate:
aggregationStrategy: "#groupedExchange"
completionSize: 100
completionTimeout: "1000"
correlationExpression:
constant: "true"
steps:
- to:
uri: kafka:my-topic In XML and YAML, register the GroupedExchangeAggregationStrategy as a bean named groupedExchange in the registry. |
The reason for this is related to how the producer handles the two different cases:
-
with the
aggregateit should process the messages in a "batch-sized chunk" semi-asynchronously (that is, send all messages in the batch and then wait for their acknowledgements) -
without that, it sends synchronously, eventually blocking on the record metadata fetch per exchange.
| the downside of this approach is an increased number of in-flight exchanges and the potential risks (even though small and rare) associated with that. |
Examples
Consuming messages from Kafka
Here is the minimal route you need to read messages from Kafka. Set groupId so that the consumer resumes from its committed offsets after a restart (see Consumer groups).
-
Java
-
XML
-
YAML
from("kafka:test?brokers=localhost:9092&groupId=my-group")
.log("Message received from Kafka : ${body}")
.log(" on the topic ${headers[CamelKafkaTopic]}")
.log(" on the partition ${headers[CamelKafkaPartition]}")
.log(" with the offset ${headers[CamelKafkaOffset]}")
.log(" with the key ${headers[CamelKafkaKey]}") <route>
<from uri="kafka:test?brokers=localhost:9092&groupId=my-group"/>
<log message="Message received from Kafka : ${body}"/>
<log message=" on the topic ${headers[CamelKafkaTopic]}"/>
<log message=" on the partition ${headers[CamelKafkaPartition]}"/>
<log message=" with the offset ${headers[CamelKafkaOffset]}"/>
<log message=" with the key ${headers[CamelKafkaKey]}"/>
</route> - route:
from:
uri: kafka:test
parameters:
brokers: "localhost:9092"
groupId: my-group
steps:
- log: "Message received from Kafka : ${body}"
- log: " on the topic ${headers[CamelKafkaTopic]}"
- log: " on the partition ${headers[CamelKafkaPartition]}"
- log: " with the offset ${headers[CamelKafkaOffset]}"
- log: " with the key ${headers[CamelKafkaKey]}" If you need to consume messages from multiple topics, you can use a comma separated list of topic names.
-
Java
-
XML
-
YAML
from("kafka:test,test1,test2?brokers=localhost:9092&groupId=my-group")
.log("Message received from Kafka : ${body}")
.log(" on the topic ${headers[CamelKafkaTopic]}")
.log(" on the partition ${headers[CamelKafkaPartition]}")
.log(" with the offset ${headers[CamelKafkaOffset]}")
.log(" with the key ${headers[CamelKafkaKey]}") <route>
<from uri="kafka:test,test1,test2?brokers=localhost:9092&groupId=my-group"/>
<log message="Message received from Kafka : ${body}"/>
<log message=" on the topic ${headers[CamelKafkaTopic]}"/>
<log message=" on the partition ${headers[CamelKafkaPartition]}"/>
<log message=" with the offset ${headers[CamelKafkaOffset]}"/>
<log message=" with the key ${headers[CamelKafkaKey]}"/>
</route> - route:
from:
uri: "kafka:test,test1,test2"
parameters:
brokers: "localhost:9092"
groupId: my-group
steps:
- log: "Message received from Kafka : ${body}"
- log: " on the topic ${headers[CamelKafkaTopic]}"
- log: " on the partition ${headers[CamelKafkaPartition]}"
- log: " with the offset ${headers[CamelKafkaOffset]}"
- log: " with the key ${headers[CamelKafkaKey]}" It’s also possible to subscribe to multiple topics giving a pattern as the topic name and using the topicIsPattern option.
-
Java
-
XML
-
YAML
from("kafka:test.*?brokers=localhost:9092&groupId=my-group&topicIsPattern=true")
.log("Message received from Kafka : ${body}")
.log(" on the topic ${headers[CamelKafkaTopic]}")
.log(" on the partition ${headers[CamelKafkaPartition]}")
.log(" with the offset ${headers[CamelKafkaOffset]}")
.log(" with the key ${headers[CamelKafkaKey]}") <route>
<from uri="kafka:test.*?brokers=localhost:9092&groupId=my-group&topicIsPattern=true"/>
<log message="Message received from Kafka : ${body}"/>
<log message=" on the topic ${headers[CamelKafkaTopic]}"/>
<log message=" on the partition ${headers[CamelKafkaPartition]}"/>
<log message=" with the offset ${headers[CamelKafkaOffset]}"/>
<log message=" with the key ${headers[CamelKafkaKey]}"/>
</route> - route:
from:
uri: "kafka:test.*"
parameters:
brokers: "localhost:9092"
groupId: my-group
topicIsPattern: true
steps:
- log: "Message received from Kafka : ${body}"
- log: " on the topic ${headers[CamelKafkaTopic]}"
- log: " on the partition ${headers[CamelKafkaPartition]}"
- log: " with the offset ${headers[CamelKafkaOffset]}"
- log: " with the key ${headers[CamelKafkaKey]}" When consuming messages from Kafka, you can use your own offset management and not delegate this management to Kafka. To keep the offsets, the component needs a StateRepository implementation such as FileStateRepository. This bean should be available in the registry. Here how to use it :
The FileStateRepository bean must be registered in the Camel registry before it can be referenced by the route. |
FileStateRepository repository = FileStateRepository.fileStateRepository(new File("/path/to/repo.dat"));
// Bind this repository into the Camel registry
Registry registry = createCamelRegistry();
registry.bind("offsetRepo", repository); -
Java
-
XML
-
YAML
from("kafka:my-topic?brokers=localhost:9092&groupId=A&autoOffsetReset=earliest&offsetRepository=#offsetRepo")
.to("mock:result"); <route>
<from uri="kafka:my-topic?brokers=localhost:9092&groupId=A&autoOffsetReset=earliest&offsetRepository=#offsetRepo"/>
<to uri="mock:result"/>
</route> - route:
from:
uri: kafka:my-topic
parameters:
brokers: "localhost:9092"
groupId: A
autoOffsetReset: earliest
offsetRepository: "#offsetRepo"
steps:
- to:
uri: mock:result Producing messages to Kafka
Here is the minimal route you need to produce messages to Kafka.
-
Java
-
XML
-
YAML
from("direct:start")
.setBody(constant("Message from Camel"))
.setHeader("CamelKafkaKey", constant("Camel"))
.to("kafka:test?brokers=localhost:9092"); <route>
<from uri="direct:start"/>
<setBody>
<constant>Message from Camel</constant>
</setBody>
<setHeader name="CamelKafkaKey">
<constant>Camel</constant>
</setHeader>
<to uri="kafka:test?brokers=localhost:9092"/>
</route> - route:
from:
uri: direct:start
steps:
- setBody:
constant: "Message from Camel"
- setHeader:
name: CamelKafkaKey
constant: "Camel"
- to:
uri: kafka:test
parameters:
brokers: "localhost:9092" The header name is CamelKafkaKey. |
SSL configuration
You have two different ways to configure the SSL communication on the Kafka component.
The first way is through the many SSL endpoint parameters:
-
Java
-
XML
-
YAML
from("kafka:my-topic?brokers=localhost:9092&groupId=A&sslKeystoreLocation=/path/to/keystore.jks&sslKeystorePassword=changeit&sslKeyPassword=changeit&securityProtocol=SSL")
.to("mock:result"); <route>
<from uri="kafka:my-topic?brokers=localhost:9092&groupId=A&sslKeystoreLocation=/path/to/keystore.jks&sslKeystorePassword=changeit&sslKeyPassword=changeit&securityProtocol=SSL"/>
<to uri="mock:result"/>
</route> - route:
from:
uri: kafka:my-topic
parameters:
brokers: "localhost:9092"
groupId: A
sslKeystoreLocation: "/path/to/keystore.jks"
sslKeystorePassword: changeit
sslKeyPassword: changeit
securityProtocol: SSL
steps:
- to:
uri: mock:result The second way is to use the sslContextParameters endpoint parameter:
KeyStoreParameters ksp = new KeyStoreParameters();
ksp.setResource("/path/to/keystore.jks");
ksp.setPassword("changeit");
KeyManagersParameters kmp = new KeyManagersParameters();
kmp.setKeyStore(ksp);
kmp.setKeyPassword("changeit");
SSLContextParameters scp = new SSLContextParameters();
scp.setKeyManagers(kmp);
Registry registry = createCamelRegistry();
registry.bind("ssl", scp); -
Java
-
XML
-
YAML
from("kafka:my-topic?brokers=localhost:9092&groupId=A&sslContextParameters=#ssl&securityProtocol=SSL")
.to("mock:result"); <route>
<from uri="kafka:my-topic?brokers=localhost:9092&groupId=A&sslContextParameters=#ssl&securityProtocol=SSL"/>
<to uri="mock:result"/>
</route> - route:
from:
uri: kafka:my-topic
parameters:
brokers: "localhost:9092"
groupId: A
sslContextParameters: "#ssl"
securityProtocol: SSL
steps:
- to:
uri: mock:result For details on how sslContextParameters is applied to Kafka TLS connections, see the TLS with sslContextParameters section above.