【问题标题】:In reactive programming how to elegantly close the connection in the database connection pool在反应式编程中如何优雅地关闭数据库连接池中的连接
【发布时间】:2021-07-24 09:55:14
【问题描述】:

最近我在学习 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&lt; Void&gt; 对象,但我不知道如何同时处理两个数据流(Mono&lt; Result&gt; 和Publish&lt; Void&gt;)!

有人可以帮我吗?

【问题讨论】:

  • 嗨,欢迎来到 stackoverflow。如您所知,最佳实践是将代码文本包含在问题正文中,而不是作为图像。您可以使用“编辑”按钮更新您的帖子。 (在这篇关于 meta 的帖子中查看此建议背后的讨论:Please do not upload images of code/errors when asking a question)。

标签: java spring mysql-connector reactive webflux


【解决方案1】:

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

类似这样的:

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

【讨论】:

    猜你喜欢
    • 2019-06-27
    • 2015-06-27
    • 2015-06-25
    • 2021-06-03
    • 1970-01-01
    • 2012-10-29
    • 1970-01-01
    • 2014-04-09
    • 1970-01-01
    相关资源
    最近更新 更多