Skip to main content

dawdler-kafka-core

Module Introduction​

Provides Kafka consumer and producer support.

1. Add the dependency in pom​

<groupId>club.dawdler</groupId>
<artifactId>dawdler-kafka-core</artifactId>

2. properties file description​

# Kafka server addresses, multiple addresses supported separated by commas
bootstrap.servers=localhost:9092
# Consumer group ID
group.id=your-group-id
# Whether to commit offsets automatically
enable.auto.commit=true
# Interval for automatically committing offsets (unit: milliseconds)
auto.commit.interval.ms=1000
# Session timeout (unit: milliseconds)
session.timeout.ms=10000
# Heartbeat interval (unit: milliseconds)
heartbeat.interval.ms=3000
# Maximum number of records per poll
max.poll.records=500
# Maximum interval between two polls (milliseconds). dawdler's failure retry relies on partition pause/resume to redeliver, so this must be configured explicitly
# Must satisfy: max.poll.interval.ms > maxRetries * retryBackoffMs, otherwise a rebalance will be triggered during retries and cause duplicate consumption
max.poll.interval.ms=300000
# Maximum number of bytes the consumer fetches each time
fetch.max.bytes=52428800
# Maximum number of bytes returned by the consumer per partition at a time
max.partition.fetch.bytes=10485760
# Consumer key deserializer
key.deserializer=org.apache.kafka.common.serialization.StringDeserializer
# Consumer value deserializer
value.deserializer=org.apache.kafka.common.serialization.ByteArrayDeserializer
# Consumer offset reset policy (options: earliest, latest, none); lower priority than the annotation configuration
# If not configured, the Kafka official default latest is used, and when the consumer group has no committed offset the messages during shutdown are skipped; configure earliest if you need no message loss
auto.offset.reset=earliest
# Producer ack mechanism
acks=all
# Number of producer retries
retries=3
# Producer batch send size
batch.size=16384
# Producer linger time (unit: milliseconds)
linger.ms=1
# Producer buffer size
buffer.memory=33554432
# Producer key serializer
key.serializer=org.apache.kafka.common.serialization.StringSerializer
# Producer value serializer
value.serializer=org.apache.kafka.common.serialization.ByteArraySerializer
# Security protocol (optional)
security.protocol=SASL_PLAINTEXT # or SASL_SSL
# SASL mechanism (optional)
sasl.mechanism=PLAIN # or GSSAPI, SCRAM-SHA-256, SCRAM-SHA-512
# JAAS configuration (optional)
sasl.jaas.config=org.apache.kafka.common.security.plain.PlainLoginModule required username="your-username" password="your-password";
# Kerberos service name (when using GSSAPI)
sasl.kerberos.service.name=kafka
# Kerberos kinit command (optional, when using GSSAPI)
sasl.kerberos.kinit.cmd=/usr/bin/kinit
# Kerberos ticket renewal window factor (optional, when using GSSAPI)
sasl.kerberos.ticket.renew.window.factor=0.8
# Kerberos ticket renewal jitter (optional, when using GSSAPI)
sasl.kerberos.ticket.renew.jitter=0.05
# Kerberos minimum time before relogin (milliseconds) (optional, when using GSSAPI)
sasl.kerberos.min.time.before.relogin=60000
# Kerberos keytab file path (optional, when using GSSAPI, classpath paths supported)
# The keytab file is automatically copied to a temporary file, and the temporary file path is automatically appended to the JAAS configuration
kerberos.keytab=/etc/kafka/kafka.keytab
# Kerberos principal (optional, when using GSSAPI)
kerberos.principal=kafka/client@REALM.COM
# Kerberos krb5.conf file path (JVM system property, optional, when using GSSAPI)
# Supports classpath paths (such as krb5.conf) or absolute filesystem paths (such as /etc/krb5.conf)
# classpath paths are automatically copied to a temporary file
kerberos.krb5.conf=/etc/krb5.conf

The configuration file supports multiple environments, the unified configuration center, encryption, and variable substitution. See Multi-environment configuration.

3. SASL/Kerberos (GSSAPI) authentication configuration​

3.1 SASL/PLAIN authentication configuration example​

# SASL/PLAIN authentication
security.protocol=SASL_PLAINTEXT
sasl.mechanism=PLAIN
sasl.jaas.config=org.apache.kafka.common.security.plain.PlainLoginModule required username="admin" password="admin-secret";

3.2 SASL/SCRAM-SHA-256 authentication configuration example​

# SASL/SCRAM-SHA-256 authentication
security.protocol=SASL_PLAINTEXT
sasl.mechanism=SCRAM-SHA-256
sasl.jaas.config=org.apache.kafka.common.security.scram.ScramLoginModule required username="admin" password="admin-secret";

3.3 SASL/GSSAPI (Kerberos) authentication configuration example​

3.3.1 Using a keytab file​
# SASL/GSSAPI (Kerberos) authentication - using a keytab file on the classpath
security.protocol=SASL_PLAINTEXT
sasl.mechanism=GSSAPI
# keyTab does not need to be specified in the JAAS configuration; it is read from kerberos.keytab and appended automatically
sasl.jaas.config=com.sun.security.auth.module.Krb5LoginModule required;
sasl.kerberos.service.name=kafka
sasl.kerberos.kinit.cmd=/usr/bin/kinit
sasl.kerberos.ticket.renew.window.factor=0.8
sasl.kerberos.ticket.renew.jitter=0.05
sasl.kerberos.min.time.before.relogin=60000
# keytab file path, supports classpath paths (such as kafka.keytab) or absolute paths (such as /etc/kafka/kafka.keytab)
kerberos.keytab=kafka.keytab
# Kerberos principal (optional, automatically appended to the JAAS configuration)
kerberos.principal=kafka/client@REALM.COM
kerberos.krb5.conf=/etc/krb5.conf

Notes:

  • kerberos.keytab and kerberos.krb5.conf support two path formats:

    • classpath path: such as kafka.keytab; the file must be placed in the src/main/resources directory
    • absolute filesystem path: such as /etc/kafka/kafka.keytab; the path starts with / and the original path is used directly
  • Example of the final generated JAAS configuration:

    com.sun.security.auth.module.Krb5LoginModule required useKeyTab=true keyTab="/tmp/kerberos-1234567890.keytab" principal="kafka/client@REALM.COM";

4. KafkaInjector annotation​

Used to inject a KafkaProvider

The value of the KafkaInjector annotation takes fileName as the configuration file name (without the .properties suffix).

For details see:

dawdler-server-plug-kafka implements the injection feature on the dawdler-server side.

dawdler-client-plug-kafka implements the injection feature on the web side.

5. KafkaListener annotation​

Used to mark a method as listening for messages on a specified topic. In dawdler's implementation, a single class can have multiple methods marked with the KafkaListener annotation.

/**
*
* Marks whether a method is a Kafka consumer. The format of this method is fixed: void methodName(Message message)
* @author jackson.song
* @version V1.0
*/
@Retention(value = RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD })
public @interface KafkaListener {

/**
* Specifies the Kafka configuration file name
*/
String fileName();

/**
* Topic name
*/
String topic();

/**
* Whether to commit offsets automatically
* true: the Kafka client commits automatically according to auto.commit.interval.ms
* false: commit manually after each batch of messages (the records returned by one poll) is processed, with at-least-once semantics
*/
boolean autoCommit() default true;

/**
* Session timeout (unit: milliseconds)
*/
int sessionTimeoutMs() default 10000;

/**
* Heartbeat interval (unit: milliseconds)
*/
int heartbeatIntervalMs() default 3000;

/**
* Maximum number of records per poll
*/
int maxPollRecords() default 500;

/**
* Number of consumer threads; each thread holds an independent consumer instance and they share group.id
* It is recommended not to exceed the number of partitions of the topic
*/
int consumerThreads() default 1;

/**
* Shutdown timeout (milliseconds). The timeout for waiting for this consumer task to complete during graceful shutdown
* Different consumers can be configured with different timeouts
*/
int shutdownTimeoutMs() default 5000;

/**
* Consumer offset reset policy (options: earliest, latest, none)
* If not configured, the Kafka official default latest is used
* Priority: annotation > configuration file > Kafka default
*/
String autoOffsetReset() default "";

/**
* Message processing failure policy, takes effect after retries are exhausted
*/
FailurePolicy failurePolicy() default FailurePolicy.RETRY;

/**
* Number of retries for a single message before applying the failure policy; 0 means process only once
* Within a single delivery at most 1 extra immediate retry is made; the remaining retries are done by redelivering after the failed partition is paused/resumed
* Attempt counts accumulate across deliveries by (topic, partition, offset), and restart counting after a process restart
*/
int maxRetries() default 3;

/**
* Retry interval (milliseconds), the interval before the failed partition is redelivered after being paused.
* Retries do not block the consumer thread; the consume loop keeps polling during the pause
*/
long retryBackoffMs() default 1000L;

/**
* Dead letter topic, only effective when failurePolicy=DEAD_LETTER; when empty, topic + ".DLQ" is used
*/
String deadLetterTopic() default "";

enum FailurePolicy {
RETRY, // Do not commit the offset; seek back and pause the partition, then keep retrying (at-least-once, the partition is blocked)
DEAD_LETTER, // Commit the offset only after successfully delivering to the dead letter topic
SKIP, // Log and commit the offset (at-most-once, messages will be lost)
STOP // Stop the consumer thread without committing the failed message, waiting for restart/rebalance to redeliver
}

}

5.1 Graceful shutdown timeout configuration​

Each @KafkaListener can configure shutdownTimeoutMs independently. During graceful shutdown, the consumer thread pool is awaited by that timeout to complete the current task:

@KafkaListener(
fileName = "orderKafka",
topic = "order-topic",
shutdownTimeoutMs = 10000 // the order consumer waits 10 seconds
)
public void handleOrder(Message message) {
// Handle the order message
}

@KafkaListener(
fileName = "logKafka",
topic = "log-topic",
shutdownTimeoutMs = 3000 // the log consumer waits 3 seconds
)
public void handleLog(Message message) {
// Handle the log message
}

5.2 Multi-threaded consumption​

consumerThreads specifies the number of consumer threads. KafkaConsumer is not thread-safe (concurrent calls to methods such as poll() from multiple threads throw ConcurrentModificationException), so dawdler creates an independent KafkaConsumer instance for each consumer thread. Multiple instances share the group.id from the configuration file, and the partitions of the topic are automatically assigned by Kafka within the consumer group.

Notes:

  • When the number of consumer threads exceeds the number of topic partitions, the extra consumer threads are idle; it is recommended that consumerThreads does not exceed the number of partitions
  • During graceful shutdown, wakeup() (the only thread-safe method of KafkaConsumer) is used to wake up consumer threads blocked in poll(); after the batch of messages being processed is finished, the thread exits and closes the consumer it holds (in auto-commit mode close() commits the remaining offsets; in manual commit mode the offsets have already been committed batch by batch by the consume loop)

5.3 Offset commit semantics and exception handling​

The autoCommit of @KafkaListener determines how offsets are committed:

  • autoCommit = true (default): offsets are committed automatically by the Kafka client according to auto.commit.interval.ms. On failure dawdler first seeks the position back to the failed message, so the failed message will not be skipped over by an automatic commit; but a process crash may still cause duplicate consumption (at-least-once)
  • autoCommit = false: dawdler commits precisely per partition, only committing positions before the failed message (commitSync(Map)), and never commits the failed message or the messages after it

Failure handling

Retries after the business method throws an exception do not block the consumer thread (no sleep):

  • Within a single delivery: at most 1 immediate retry (to cope with momentary jitter)
  • Remaining retries: seek back to the failed position and pause that partition, then resume and redeliver after retryBackoffMs; during the pause the consume loop keeps polling, so max.poll.interval.ms will not time out
  • Attempt counts accumulate across deliveries by (topic, partition, offset) (valid only within the process, restarting counting after a process restart); after reaching maxRetries retries (that is, the first processing plus maxRetries retries), the message is handled according to failurePolicy

After retries are exhausted, the message is handled according to failurePolicy:

failurePolicyBehaviorSemantics
RETRY (default)Do not commit the failed message; seek back to the failed position and pause that partition, then keep retrying after retryBackoffMs (counting restarts after the retry budget is exhausted, retrying indefinitely)at-least-once; the failed partition is blocked and poison messages need manual handling
DEAD_LETTERDeliver to deadLetterTopic (default topic + ".DLQ"), and commit only after success; if delivery fails, do not commit and keep retrying (after the budget is exhausted the redelivery only retries the dead letter delivery and no longer executes the business method)at-least-once + dead letter
SKIPLog an ERROR and commitat-most-once, messages are lost
STOPStop that consumer thread without committing the failed message, waiting for restart or rebalance to redeliverat-least-once, requires manual intervention/restart to recover

After a message in a partition fails, the remaining messages in the same batch are not executed, avoiding skipping the failed message or producing out-of-order side effects; other partitions are unaffected.

Dead letter messages retain the original key/value and original headers, and four headers are attached: dawdler.dlq.original.topic, dawdler.dlq.original.partition, dawdler.dlq.original.offset, dawdler.dlq.error, to facilitate troubleshooting and compensation.

Configuration example:

// Recommended production configuration: retry immediately once within a single delivery, with the remaining retries done by redelivering after partition pause/resume,
// and enter the dead letter topic after accumulating 3 retries across deliveries; no message loss and no partition blocking
// max.poll.interval.ms must be configured explicitly in the configuration file, and must satisfy
// max.poll.interval.ms > maxRetries * retryBackoffMs (e.g. 3 * 1000 = 3 seconds; the default 5 minutes already satisfies this)
@KafkaListener(
fileName = "orderKafka",
topic = "order-topic",
autoCommit = false,
maxRetries = 3,
retryBackoffMs = 1000,
failurePolicy = KafkaListener.FailurePolicy.DEAD_LETTER,
deadLetterTopic = "order-topic.DLQ"
)
public void handleOrder(Message message) {
// Handle the order message
}

Notes:

  • Stop on commit failure: with autoCommit = false, if commitSync throws an exception (including when it still fails after retrying after wakeup), that consumer thread exits immediately: it neither commits nor continues consuming subsequent batches. If it kept consuming, later commits of larger offsets would overwrite the ineffective positions, and after restart/rebalance this batch of messages would be silently skipped (lost). After the thread exits, the partitions are reassigned through rebalance and redelivered from the last committed position (at-least-once)
  • max.poll.interval.ms must be configured explicitly (configuration file, Kafka default 5 minutes): dawdler's failure retry relies on partition pause/resume redelivery, and a message from first failure until retries are exhausted spans multiple deliveries with a total duration of about maxRetries * retryBackoffMs. It must satisfy max.poll.interval.ms significantly greater than maxRetries * retryBackoffMs, otherwise a rebalance will be triggered during retries, causing the failed message to be consumed repeatedly and even restarting the count repeatedly. The Kafka official default (5 minutes) is usually sufficient when not configured, but when increasing maxRetries or retryBackoffMs you must increase max.poll.interval.ms accordingly
  • DEAD_LETTER requires producer configuration in the same configuration file (key.serializer, value.serializer, acks, retries, etc.); otherwise startup fails directly instead of degrading into silently losing messages
  • Attempt counts are accumulated only within the process by (topic, partition, offset), restarting after a process restart or rebalance; consumption logic must still be idempotent
  • In RETRY mode a poison message occupies that partition for a long time (the budget is exhausted and counting restarts, retrying indefinitely); in production it is recommended to use DEAD_LETTER or STOP together with alerting
  • Consumption logic must still be idempotent: retries, rebalances and process crashes may all cause duplicate delivery
  • With autoCommit = false, on first startup the consumer group has no committed offset, so the starting point is determined by auto.offset.reset (Kafka official default is latest, i.e. start from the latest messages). To start consuming from the earliest messages, explicitly configure earliest through the annotation autoOffsetReset or the configuration file auto.offset.reset
  • enable.auto.commit in the configuration file does not take effect; the consumer side follows the annotation autoCommit

6. KafkaProvider class​

// Push a message to the specified topic
public RecordMetadata publish(String topic, byte[] message) throws Exception

// Push a message to the specified topic with a key
public RecordMetadata publish(String topic, String key, byte[] message) throws Exception

// Push a message to the specified topic with a key and headers
public RecordMetadata publish(String topic, String key, byte[] message, Headers headers) throws Exception

// Push a message to the specified topic, asynchronously via callback
public Future<RecordMetadata> publish(String topic, byte[] message, Callback callback) throws Exception

// Push a message to the specified topic with a key, asynchronously via callback
public Future<RecordMetadata> publish(String topic, String key, byte[] message, Callback callback) throws Exception

7. Usage outside the dawdler architecture​

// By calling the getKafkaProvider method of KafkaProviderFactory

public static KafkaProvider getKafkaProvider(String fileName);

// Use this method to obtain a KafkaProvider; fileName does not include the .properties suffix.

// For example: if fileName is myKafka, you need to create a configuration file myKafka.properties in the project's classpath.

Note: KafkaProviders running on the client and server sides do not need to be closed manually; dawdler closes the related resources automatically.

When used outside the dawdler architecture, you need to call KafkaProviderFactory.shutdownAll(); to release resources.