简体   繁体   English

在反应式编程中如何优雅地关闭数据库连接池中的连接

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

Recently I am learning Spring WebFlux.最近在学习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!我注意到close函数会返回一个Publish< Void>对象,但我不知道如何一起处理两个数据流( Mono< Result>Publish< Void> )!

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.您可以将doFinally()处理程序附加到Mono以便无论流处理是否正常完成,它都可以确保关闭连接。

Something like this:像这样的东西:

.flatMap(c -> 
    Mono.from(c.createStatement("query goes here...")
      .execute())
      .doFinally((st) -> close(c))
 )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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