Search code examples
javaspringmysql-connectorreactivewebflux

In reactive programming how to elegantly close the connection in the database connection pool


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?


Solution

  • 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))
     )