【问题标题】:r2dbc-pool connection not released after cancelr2dbc-pool 连接取消后未释放
【发布时间】:2021-09-25 03:38:58
【问题描述】:

我对 R2DBC 池有一个奇怪的行为:我们碰巧创建了大量线程并将它们发送到 R2DBC 池以获取数据库连接。当池中的所有 R2DBC 连接都在使用中时,我们创建的线程排队等待空闲连接可用,这发生在先前使用的连接被释放时。如果我们在等待空闲连接时取消这些线程,则会发生以下行为:

  • 即使它们被取消,一些线程仍会获取连接并执行其正常的 DB 进程
  • 最重要的一点:即使所有线程都被取消并且不再处于活动状态,某些连接已被获取并且永远不会被释放。

因此,某些连接不会回到空闲状态。它们保持被获取并阻止后续连接请求获取这些特定连接。在我们重新启动服务之前,连接保持锁定状态。

值得一提的是,我们在获取连接时对数据库进行了查询(我们有一个多租户数据库,并在获取连接时使用 SET SCHEMA 来选择正确的租户)。

我编写了一个程序来重现该问题。

为了测试,我使用 maxConnection=2 的池。 在调用了几次测试方法(controller.test)之后,池中的一些连接仍然无限期地被获取(它们应该已经全部被 onCancelclose Spring 处理的语句)。这可以通过使用 jmx 来监控池很容易地证明。

我想取消请求会传播到connectionPool.create(),但是一些迭代似乎有足够的时间在接收取消之前结束preQuery,这导致连接对Spring可用用来。在这些情况下,在 TestConnectionFactory 中看不到取消,并且大约 1/3 次,Spring 不调用 connection.close,导致保持获取连接。

@Slf4j
@RestController
public class TestController {
    private final TestRepo1 testRepo1;

    @Autowired
    public TestController(
            TestRepo1 testRepo1
    ) {
        this.testRepo1 = testRepo1;
    }

    @GetMapping("test")
    Mono<Void> test(
    ) {
        // Will made 49 queries to the database.
        return Mono
                .when(
                        IntStream.range(0, 100)
                                .mapToObj(i -> Mono.defer(() ->
                                        i == 0 ? // the first element throw an error after 2 seconds, canceling all query not already done.
                                                Mono.just(0)
                                                        .delayElement(Duration.ofMillis(2000))
                                                        .doOnNext(x -> log.info("{} -> throw", x))
                                                        .then(Mono.error(new Exception("FAIL"))) :
                                                testRepo1.query(String.valueOf(i)))
                                )
                                .collect(Collectors.toList())
                )
                .then()
                .onErrorResume(e -> Mono.empty()); // avoid propagating error to http response.
    }
}
@Slf4j
public class TestConnectionFactory implements ConnectionFactory {
    private final ConnectionPool connectionPool;

    TestConnectionFactory(ConnectionPool connectionPool) {
        this.connectionPool = connectionPool;
    }

    @Override
    public Publisher<? extends Connection> create() {
       return createTenantConnection()
                .doOnNext(x -> log.info("creation transaction done"))
                .doOnCancel(() -> log.info("cancel while creation"));
    }

    private Mono<Connection> createTenantConnection() {
        return connectionPool.create()
                .flatMap(connection -> preQuery(connection));
    }

    private Mono<Connection> preQuery(Connection connection) {
        return Mono.from(connection
                .createStatement("SELECT 1;") // enough to produce the error, in our real code, this is a SET SCHEMA XXX
                .execute())
                .doOnCancel(() -> log.info("cancel during preQuery"))
                .thenReturn(connection);
    }

    @Override
    public ConnectionFactoryMetadata getMetadata() {
        return connectionPool.getMetadata();
    }
}
@Configuration
public class MyConfiguration {
    @Bean
    @Scope("singleton")
    ConnectionFactory connectionFactory(
            ConnectionPool connectionPool
    ) {
        return new TestConnectionFactory(connectionPool);
    }
}
@Slf4j
@Repository
public class TestRepo1 {
    // simple query waiting 1 second
    private static final String QUERY = "SELECT pg_sleep(1);";

    private final DatabaseClient databaseClient;

    @Autowired
    public TestRepo1(DatabaseClient databaseClient) {
        this.databaseClient = databaseClient;
    }

    public Mono<Void> query(String msg) {
        log.info("start query {}", msg);
        return databaseClient.execute(QUERY)
                .map(row -> "result")
                .first()
                .doOnCancel(() -> log.info("cancel query {}", msg))
                .doOnNext(x -> log.info("query {} result", msg))
                .then()
                .doOnTerminate(() -> log.info("terminate {}", msg));
    }
}

我们使用 org.springframework.boot 2.3.5.RELEASEio.r2dbc:r2dbc-postgresqlio.r2dbc:r2dbc-pool强>。

我们尝试升级到 io.r2dbc:r2dbc-postgresql 0.8.8.RELEASEio.r2dbc:r2dbc-pool 0.9.0.M1 但结果保持不变。

【问题讨论】:

    标签: java spring spring-data-r2dbc r2dbc r2dbc-postgresql


    【解决方案1】:

    this article about using jOOQ with R2DBC 中所述,使用 R2DBC 管理资源的一种好方法是使用Flux.usingWhen(),例如

    Flux.usingWhen(
            pool.create(),
            c -> c.createStatement("SELECT col FROM my_table").execute(),
            c -> c.close()
        )
        .flatMap(it -> it.map((r, m) -> r.get(0, String.class)))
        .doOnNext(System.out::println)
        .subscribe();
    

    这也是邮件列表中推荐的:

    并有望在未来记录在r2dbc.io 网站上:

    【讨论】:

    • 这个解决方案不适用于我们的问题,因为我们正在实现 ConnectionFactory,它将连接返回给 Spring。如果我们使用 Flux.usingWhen 进行连接创建实现,那么工厂返回给 Spring 的连接在真正使用之前就已经关闭了。我们可以使用 Flux.usingWhen 的另一个地方是在存储库中,但我们目前依赖 Spring(通过使用 DatabaseClient 或 ReactiveCrudRepository)并且从不直接处理连接。这样做需要我们手动编写当前由 Spring 处理的代码。
    猜你喜欢
    • 1970-01-01
    • 2014-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-05
    • 2015-07-29
    • 2017-06-06
    • 2015-03-26
    相关资源
    最近更新 更多