简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM