首页 > 解决方案 > vert.x 这里仍在运行一个查询-race-> SQLConnection 的错误问题

问题描述

我正在使用 vert.x SQLConnection 进行数据库连接。我在循环中使用相同的连接运行简单查询。以下是我的代码示例

 public static void test(RoutingContext routingContext) {
        Vertx vertx = Vertx.currentContext().owner();
        JsonObject configJson = new JsonObject().put("host", "mymysqldb.mycompany");
        io.vertx.ext.asyncsql.AsyncSQLClient client = PostgreSQLClient.createShared(vertx, configJson);
        client.getConnection(connectionHandler -> {
            if (connectionHandler.succeeded()) {
                SQLConnection connection = connectionHandler.result();
                for (int i = 0; i < 10; i++) {
                    System.out.println("count" + i);
                    try {
                        connection.query("select 1", selectHandler -> {
                            System.out.println("executed query");
                        });
                    } catch (Exception e) {
                        System.out.println(e);
                    }
                }
            } else {
                LOGGER.error("Error in get connection : ", connectionHandler.cause());
            }
        });
    }

但是当我运行它时,它会给我以下输出

count0
count1
com.github.mauricio.async.db.exceptions.ConnectionStillRunningQueryException: [2] - There is a query still being run here - race -> false
count2
com.github.mauricio.async.db.exceptions.ConnectionStillRunningQueryException: [2] - There is a query still being run here - race -> false
count3
com.github.mauricio.async.db.exceptions.ConnectionStillRunningQueryException: [2] - There is a query still being run here - race -> false
count4
com.github.mauricio.async.db.exceptions.ConnectionStillRunningQueryException: [2] - There is a query still being run here - race -> false
count5
com.github.mauricio.async.db.exceptions.ConnectionStillRunningQueryException: [2] - There is a query still being run here - race -> false
count6
com.github.mauricio.async.db.exceptions.ConnectionStillRunningQueryException: [2] - There is a query still being run here - race -> false
count7
com.github.mauricio.async.db.exceptions.ConnectionStillRunningQueryException: [2] - There is a query still being run here - race -> false
count8
count9
com.github.mauricio.async.db.exceptions.ConnectionStillRunningQueryException: [2] - There is a query still being run here - race -> false
executed query
executed query

我想这可能是因为它在 for 循环中异步运行查询,并且由于一次又一次地使用相同的连接,它尝试在第一个仍在运行时使用相同的连接执行第二个查询。

如果我在 for 循环本身中调用 getDatabaseConnection 方法,那么这个问题将得到解决,这样每​​个查询都可以使用不同的连接。(同样,如果循环是一千个,那么这可能是一个问题,那么将创建许多连接,但现在让我们忽略这个问题)。但是如果我想在这里使用事务,那么我必须需要创建单个连接才能进行事务处理?vert.x 或我的理解是否有任何问题。任何人都可以帮助我如何实现这一目标

标签: javaasynchronousvert.x

解决方案


推荐阅读