在MySQL JDBC連接池中,您可以通過設置connectionTimeout
參數來配置連接超時。以下是如何在不同的連接池庫中配置連接超時的示例:
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://localhost:3306/mydb");
config.setUsername("username");
config.setPassword("password");
config.setConnectionTimeout(30000); // 設置連接超時為30秒
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
HikariDataSource ds = new HikariDataSource(config);
BasicDataSource dataSource = new BasicDataSource();
dataSource.setUrl("jdbc:mysql://localhost:3306/mydb");
dataSource.setUsername("username");
dataSource.setPassword("password");
dataSource.setConnectionTimeout(30000); // 設置連接超時為30秒
dataSource.setValidationQuery("SELECT 1");
dataSource.setTestOnBorrow(true);
dataSource.setTestWhileIdle(true);
dataSource.setTimeBetweenEvictionRunsMillis(60000);
Connection connection = dataSource.getConnection();
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/mydb");
dataSource.setUser("username");
dataSource.setPassword("password");
dataSource.setConnectionTimeout(30000); // 設置連接超時為30秒
dataSource.setMinPoolSize(5);
dataSource.setMaxPoolSize(20);
dataSource.setMaxStatements(50);
dataSource.setIdleConnectionTestPeriod(3000);
Connection connection = dataSource.getConnection();
請注意,這些示例中的connectionTimeout
值是以毫秒為單位的。根據您的需求調整該值。