1

Recently I am learning Spring WebFlux. And When I try to close my connection in the connection pool, it does not work!

Code is like this:

return connectionPool.create().flatMap(connection -> {
    Mono<Result> result = Mono.from(connection.createStatement("").execute());
    connection.close();
    return result;
    })
    .flatMap(body -> Mono.from(body.map(((row, rowMetadata) -> row.get(0, String.class)))));

I have noticed that the close function would return a Publish< Void> object, but I do not know how to deal with the two dataflows (Mono< Result> and Publish< Void>) together!

Could someone help me?

Atul Dwivedi
  • 1,452
  • 16
  • 29
softgreet
  • 35
  • 3
  • 3
    Hi and welcome to stackoverflow. Just so you know, best practice is to include the text of your code in the body of your question, rather than as an image. You can update your post using the 'Edit' button. (Check out the discussion behind this advice in this post on meta: [Please do not upload images of code/errors when asking a question](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question)). – morric Jul 24 '21 at 10:11

1 Answers1

2

You can attach a doFinally() handler to the Mono so that it can make sure that connection is closed whether the stream processing completes normally or not.

Something like this:

.flatMap(c -> 
    Mono.from(c.createStatement("query goes here...")
      .execute())
      .doFinally((st) -> close(c))
 )
Atul Dwivedi
  • 1,452
  • 16
  • 29