未分类 · 2023-04-30 0

数据库连接池 HikariCP 配置

1.pom

<dependency>
    <groupId>com.zaxxer</groupId>
    <artifactId>HikariCP</artifactId>
    <version>4.0.3</version>
</dependency>

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.0.33</version>
</dependency>

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.2</version>
    <scope>test</scope>
</dependency>

2.java

@Test
public void test1() throws SQLException {
    HikariConfig hikariConfig = new HikariConfig();
    hikariConfig.setJdbcUrl("jdbc:mysql://localhost:3306/test");
    hikariConfig.setUsername("root");
    hikariConfig.setPassword("123456");
    // 默认 10,配置允许连接池达到的最大连接数(包括空闲和正在使用的)
    hikariConfig.setMaximumPoolSize(5);

    HikariDataSource ds = new HikariDataSource(hikariConfig);
    Connection conn = ds.getConnection();
    Statement statement = conn.createStatement();
    ResultSet rs = statement.executeQuery("SELECT * FROM student");
    while (rs.next()) {
        System.out.println(String.format("id: %s name: %s",
                rs.getString("id"), rs.getString("name")));
    }
    rs.close();
    statement.close();
    conn.close();
}
// TODO