阅读量:0
在MySQL JDBC连接池中,您可以通过设置connectionTimeout
参数来配置连接超时。以下是如何在不同的连接池库中配置连接超时的示例:
- HikariCP:
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);
- Apache DBCP2:
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();
- C3P0:
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
值是以毫秒为单位的。根据您的需求调整该值。