繁体   English   中英

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

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

最近在学习Spring WebFlux。 当我尝试关闭连接池中的连接时,它不起作用!

代码是这样的:

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

我注意到close函数会返回一个Publish< Void>对象,但我不知道如何一起处理两个数据流( Mono< Result>Publish< Void> )!

有人可以帮助我吗?

您可以将doFinally()处理程序附加到Mono以便无论流处理是否正常完成,它都可以确保关闭连接。

像这样的东西:

.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