mysql

MySQL JDBC连接池如何配置连接超时

小樊
81
2024-10-10 17:35:58
栏目: 云计算

在MySQL JDBC连接池中,您可以通过设置connectionTimeout参数来配置连接超时。以下是如何在不同的连接池库中配置连接超时的示例:

  1. 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);
  1. 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();
  1. 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值是以毫秒为单位的。根据您的需求调整该值。

0
看了该问题的人还看了