Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve code example for using a transactional KafkaProducer #15901

Open
wants to merge 1 commit into
base: trunk
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -192,21 +192,40 @@
* props.put("bootstrap.servers", "localhost:9092");
* props.put("transactional.id", "my-transactional-id");
* Producer<String, String> producer = new KafkaProducer<>(props, new StringSerializer(), new StringSerializer());
*
* producer.initTransactions();
*
*
* try {
* producer.beginTransaction();
* for (int i = 0; i < 100; i++)
* producer.send(new ProducerRecord<>("my-topic", Integer.toString(i), Integer.toString(i)));
* producer.commitTransaction();
* } catch (ProducerFencedException | OutOfOrderSequenceException | AuthorizationException e) {
* // We can't recover from these exceptions, so our only option is to close the producer and exit.
* producer.beginTransaction();
* try {
* for(int i = 0; i < 100; i++) {
* producer.send(new ProducerRecord<>("my-topic", Integer.toString(i), Integer.toString(i)));
* }
* } catch(KafkaException e) {
* try {
* producer.abortTransaction();
* } catch(KafkaException e2) {
* e.addSuppressed(e2);
* }
* throw e;
* }
* producer.commitTransaction();
* } catch(TimeoutException e) {
* try {
* // closing with timeout after timeout starts endless loop
* producer.close(Duration.ZERO);
* } catch(KafkaException e2) {
* e.addSuppressed(e2);
* }
* throw e;
* } catch(KafkaException e) {
* try {
* producer.close();
* } catch (KafkaException e) {
* // For all other exceptions, just abort the transaction and try again.
* producer.abortTransaction();
* } catch(KafkaException e2) {
* e.addSuppressed(e2);
* }
* throw e;
* }
*
* producer.close();
* } </pre>
* </p>
Expand Down