nil*_*esh 5 java asynchronous vert.x
我正在使用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());
}
});
}
Run Code Online (Sandbox Code Playgroud)
但是当我运行它时,它给了我以下输出
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
Run Code Online (Sandbox Code Playgroud)
我猜这可能是因为它在for循环中异步运行查询,并且一次又一次使用相同的连接,它尝试在第一个仍在运行时以相同的连接执行第二个查询。
如果我在for循环本身中调用getDatabaseConnection方法,以便每个查询可以使用不同的连接,则将解决此问题。(同样,如果循环为一千,这可能是一个问题,那么将创建许多连接,但现在暂时忽略此问题)。但是,如果我想在这里使用事务,那我必须要创建单个连接才能进行事务处理吗?vert.x或我认为有任何问题。谁能帮我实现目标
| 归档时间: |
|
| 查看次数: |
343 次 |
| 最近记录: |