我正在使用vertx-jdbc-client查询数据库。我使用了subscriptionOn(scheduler)并期望以下查询在工作线程中执行,但是它似乎在事件循环线程上执行。
如何使该查询在工作线程上执行?
import io.reactivex.Observable;
import io.reactivex.Scheduler;
import io.vertx.reactivex.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.json.JsonObject;
import io.vertx.reactivex.ext.jdbc.JDBCClient;
import io.vertx.reactivex.core.RxHelper;
public class TestVerticle extends AbstractVerticle {
JDBCClient jdbc;
@Override
public void start(Future<Void> fut) {
jdbc = JDBCClient.createNonShared(vertx,
new JsonObject().put("url", "jdbc:hsqldb:mem:test?shutdown=true")
.put("driver_class", "org.hsqldb.jdbcDriver")
.put("max_pool_size", 3));
fut.complete();
//vertx.setPeriodic(5000, id -> {
// test();
//});
test();
}
public void test() {
Scheduler scheduler = RxHelper.blockingScheduler(vertx);
jdbc.rxGetConnection()
.subscribeOn(scheduler)
.flatMap(conn -> {
Thread.sleep(3000); //Vertx BlockedThreadChecker prints warning if this is on event loop thread.
return conn.rxQuery("select 42 from (values(0))")
.doAfterTerminate(conn::close);
})
.subscribe(rs -> {
System.out.println(rs.getRows().toString() + " " + Thread.currentThread().getName());
});
//Check subscribeOn(scheduler) really works on worker thread if jdbc-client is not used.
Observable.range(1, 1).subscribeOn(scheduler).subscribe(i -> {
Thread.sleep(3000); //Vertx BlockedThreadChecker prints warning if this is on event loop thread.
System.out.println(i + " " + Thread.currentThread().getName());
});
}
}
输出:
1 vert.x-worker-thread-3
io.vertx.core.impl.BlockedThreadChecker
WARNING: Thread Thread[vert.x-eventloop-thread-2,5,main] has been blocked for 2747 ms, time limit is 2000 ms
[{"C1":42}] vert.x-eventloop-thread-2