Vertx JDBC如何在引擎盖下工作

Alm*_*zak 2 java asynchronous jdbc vert.x

我一直在使用Vertx 3个月,但现在我想知道非阻塞Vertx JDBC是如何工作的

private void selectEndedMatches(){
        this.jdbcClient.getConnection(conn->{
            if(conn.failed()){
                log.error("Can't get Vertx connection",conn.cause());
            } else{
                final SQLConnection connection = conn.result();
                connection.queryWithParams("select matchid from get5_stats_matches where matchid > ? and end_time is not null",new JsonArray().add(this.lastMatchId),this::endedMatches);
                connection.close();
            }
        });
    }


private void endedMatches(final AsyncResult<ResultSet> rs) {
        if(rs.failed()){
            log.error("Can't make select statement from JdbcVerticle",rs.cause());
        } else{
            final List<JsonArray> results = rs.result().getResults();
            final List<Integer> endedMatches = new ArrayList<>(results.size());
            for (final JsonArray result : results) {
                endedMatches.add(result.getInteger(0));
            }

        }
    }
Run Code Online (Sandbox Code Playgroud)

这里我们提供一个回调函数,当我们的select语句从DB返回结果时将执行它,但它是如何工作的.

我在文档中找不到答案 https://vertx.io/docs/vertx-jdbc-client/java/

在我看来:

Vertx使用其中一个工作线程来执行select语句而不阻塞事件循环线程.但在这种情况下,每个sql查询都需要一个单独的线程来执行.但是如果Vertx没有使用任何单独的线程来执行查询,在这种情况下,事件循环如何知道结果来自DB,使用线程非常简单,事件循环可以检查jdbc查询使用的线程的当前状态,以及如果状态已准备就绪,则意味着Event循环应该执行回调

我对么?

Ale*_*hin 8

一般来说,你是对的.
你可以自己看一下:

方法queryWithParams()调用execute():

public SQLConnection queryWithParams(String sql, JsonArray params, Handler<AsyncResult<ResultSet>> resultHandler) {
    new JDBCQuery(vertx, helper, options, ctx, sql, params).execute(conn, statementsQueue, resultHandler);
    return this;
  }
Run Code Online (Sandbox Code Playgroud)

而且execute()看起来是这样的:

public void execute(Connection conn, TaskQueue statementsQueue, Handler<AsyncResult<T>> resultHandler) {
    ctx.executeBlocking(future -> handle(conn, future), statementsQueue, resultHandler);
}
Run Code Online (Sandbox Code Playgroud)

你可能想知道它ctx来自哪里.它在JDBCClientImpl:

public SQLClient getConnection(Handler<AsyncResult<SQLConnection>> handler) {
    Context ctx = vertx.getOrCreateContext();
    getConnection(ctx, ar -> ctx.runOnContext(v -> handler.handle(ar)));
    return this;
  }
Run Code Online (Sandbox Code Playgroud)

而你的查询是由普通老人执行的 ExecutorService