You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/src/main/asciidoc/kafka.adoc
+10-9
Original file line number
Diff line number
Diff line change
@@ -2956,9 +2956,7 @@ NOTE: If you use Hibernate Reactive, look at <<writing-entities-managed-by-hiber
2956
2956
2957
2957
Because we write to a database, we must run this method in a transaction.
2958
2958
Yet, sending the entity to Kafka happens asynchronously.
2959
-
The operation returns a `CompletionStage` (or a `Uni` if you use a `MutinyEmitter`) reporting when the operation completes.
2960
-
We must be sure that the transaction is still running until the object is written.
2961
-
Otherwise, you may access the object outside the transaction, which is not allowed.
2959
+
We can achieve this by using `.sendAndAwait()` or `.sendAndForget()` on the `MutinyEmitter`, or `.send().toCompletableFuture().join()` on the `Emitter`.
2962
2960
2963
2961
To implement this process, you need the following approach:
public CompletionStage<Void> storeAndSendToKafka(Fruit fruit) { // <2>
2983
+
@Transactional // <1>
2984
+
public void storeAndSendToKafka(Fruit fruit) { // <2>
2987
2985
fruit.persist();
2988
-
return emitter.send(new FruitDto(fruit)); // <3>
2986
+
emitter.sendAndAwait(new FruitDto(fruit)); // <3>
2989
2987
}
2990
2988
}
2991
2989
----
2992
2990
<1> As we are writing to the database, make sure we run inside a transaction
2993
-
<2> The method receives the fruit instance to persist. It returns a `CompletionStage` which is used for the transaction demarcation. The transaction is committed when the return `CompletionStage` completes. In our case, it's when the message is written to Kafka.
2991
+
<2> The method receives the fruit instance to persist.
2994
2992
<3> Wrap the managed entity inside a Data transfer object and send it to Kafka.
2995
2993
This makes sure that managed entity is not impacted by the Kafka serialization.
2994
+
Then await the completion of the operation before returning.
2995
+
2996
+
NOTE: You should not return a `CompletionStage` or `Uni` when using `@Transactional`, as all transaction commits will happen on a single thread, which impacts performance.
0 commit comments