JDBC Connection Pool
HikariCP
依赖:https://central.sonatype.com/artifact/com.zaxxer/HikariCP
<dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> </dependency> <dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> </dependency>
使用
// Properties properties = new Properties(); // properties.load(this.getClass().getClassLoader().getResourceAsStream("hikaricp.properties")); // properties.setProperty("dataSourceClassName", "org.postgresql.ds.PGSimpleDataSource"); // properties.setProperty("dataSource.user", "test"); // properties.setProperty("dataSource.password", "test"); // properties.setProperty("dataSource.databaseName", "mydb"); // properties.put("dataSource.logWriter", new PrintWriter(System.out)); // HikariConfig config = new HikariConfig(properties); // HikariConfig config = new HikariConfig(this.getClass().getClassLoader().getResource("hikaricp.properties").getPath()); HikariConfig config = new HikariConfig(); config.setDriverClassName("com.mysql.cj.jdbc.Driver"); config.setJdbcUrl("jdbc:mysql://localhost:3306/employees"); config.setUsername("root"); config.setPassword("root"); config.addDataSourceProperty("cachePrepStmts", "true"); config.addDataSourceProperty("prepStmtCacheSize", "250"); config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); // config.addDataSourceProperty("logWriter", new PrintWriter(System.out)); HikariDataSource dataSource = new HikariDataSource(config); dataSource.setPassword("root"); Connection connection = dataSource.getConnection(); connection.close(); dataSource.close();
Druid
依赖:https://central.sonatype.com/artifact/com.alibaba/druid
<dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> </dependency>
使用
// Properties properties = new Properties(); // properties.load(this.getClass().getResourceAsStream("druid.properties")); // DataSource dataSource = DruidDataSourceFactory.createDataSource(properties); DruidDataSource dataSource = new DruidDataSource(); dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://localhost:3306/employees"); dataSource.setUsername("root"); dataSource.setPassword("root"); DruidPooledConnection connection = dataSource.getConnection(); connection.close(); dataSource.close();