Java Hikari无法创建池连接
我需要实现与Hikari库的JDBC池连接,但我无法让它工作。我的代码如下:Java Hikari无法创建池连接,java,connection-pooling,Java,Connection Pooling,我需要实现与Hikari库的JDBC池连接,但我无法让它工作。我的代码如下: public class DataSource { private static HikariConfig config = new HikariConfig(); private static HikariDataSource ds; static { config.setJdbcUrl("jdbc:sqlserver://localhost:1433;database=Te
public class DataSource {
private static HikariConfig config = new HikariConfig();
private static HikariDataSource ds;
static {
config.setJdbcUrl("jdbc:sqlserver://localhost:1433;database=Test;integratedSecurity=true;");
config.setUsername("****");
config.setPassword("*********");
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
ds = new HikariDataSource(config);
ds.setMaximumPoolSize(100);
ds.setMinimumIdle(5);
}
private DataSource() {
}
public static Connection getConnection() throws SQLException {
HikariPool hikariPool = new HikariPool(config);
System.out.println("POOL Active Connections -- " + hikariPool.getActiveConnections() + " Total " + hikariPool.getTotalConnections());
return ds.getConnection();
}
}
当我询问活动连接的数量时。它总是以1个活动连接进行响应
您能告诉我一些解决此问题的方法吗?是否可能只有1个活动连接和5个空闲连接?您只发出一个请求,重用一个连接而不是其他连接是有意义的,特别是在单线程环境中。您在每次调用时都要创建一个新的配置,请参阅静态配置。我试图在Hikari中复制许多连接,但我做不到。你有没有任何例子可以让我看看Hikari如何生成许多活动连接?你读过我之前的评论吗?是否引用静态变量HikariConfig而不是每次调用时创建的本地HikariConfig?HikariPool*需要创建HikariPool一次。
public class MainSample {
private static final Logger logger = LoggerFactory.getLogger(MainSample.class);
public static void loadDriver(String driverClassName) throws ClassNotFoundException {
Class.forName(driverClassName);
}
public static void main(String [] args) throws SQLException, ClassNotFoundException {
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
String threadName = Thread.currentThread().getName();
System.out.println("POOL " + threadName);
try {
fechData();
} catch (SQLException e) {
e.printStackTrace();
}
});
ExecutorService executor1 = Executors.newSingleThreadExecutor();
executor1.submit(() -> {
String threadName = Thread.currentThread().getName();
System.out.println("POOL " + threadName);
try {
fechData();
} catch (SQLException e) {
e.printStackTrace();
}
});
ExecutorService executor2 = Executors.newSingleThreadExecutor();
executor2.submit(() -> {
String threadName = Thread.currentThread().getName();
System.out.println("POOL " + threadName);
try {
fechData();
} catch (SQLException e) {
e.printStackTrace();
}
});
}