当我使用CompletableFuture测试数据库连接时,对DAO类的调用永远不会发生。线程永远不会完成。
当我尝试通过直接DAO调用类在主线程中执行相同的操作时,效果很好
以下代码永远无法完成呼叫
CompletableFuture.supplyAsync(() -> {
try {
LOG.info("Testing My DB Connection");
return this.myDBDao.testConnection();
} catch(SQLException sqlE) {
return false;
}
}, this.asyncExecutor).thenAccept(val -> {
if(val) {
LOG.info("My DB Connection Test SUCCESS");
} else {
throw new RuntimeException("CONNECTION TO MY DB FAILED");
}
}).join();
以下代码可以正常工作
try {
if(this.myDBDao.testConnection()) {
LOG.info("Testing My DB Connection");
} else {
throw new RuntimeException("CONNECTION TO MY DB FAILED");
}
} catch(SQLException sqlE) {
throw new RuntimeException("CONNECTION TO MY DB FAILED");
}
DAO方法
private static final String TEST_CON_QUERY = "select 'TRUE' as val from dual";
public boolean testConnection() throws SQLException {
LOG.info("testConnection from DAO: " + this.jdbcTemplate.getDataSource());
return this.jdbcTemplate.query(TEST_CON_QUERY, (rs) -> {
return (rs.next()) ? rs.getBoolean("VAL") : false;
});
}
数据源和连接池
@Bean(name = "myDBTemplate")
JdbcTemplate myJDBCTemplate() throws SQLException {
HikariConfig config = new HikariConfig();
config.setJdbcUrl(******);
config.setUsername(******);
config.setPassword(******);
config.setMaximumPoolSize(50);
config.setMinimumIdle(10);
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
config.setPoolName("myDBPool");
return new JdbcTemplate(new HikariDataSource(config));
}
执行人
@Bean(name = "asyncExecutor")
public ExecutorService getAsyncExecutor() {
return Executors.newCachedThreadPool();
}
为什么CompletableFuture中的代码永远无法调用testConnection()方法?