在本教程中,我们将介绍 HikariCP 并展示如何在 Java 应用程序中设置 HicariCP 连接池。在我们的应用程序中,我们向 MySQL 数据库发出请求。
HikariCP是可靠的高性能 JDBC 连接池。连接池 是维护的数据库连接缓存,以便在将来需要对数据库的请求时可以重用连接。连接池可能会显着降低整体资源使用量。
Java 数据库连接 (JDBC)是用于访问关系数据库的 Java API。它提供了查询和更新数据库中数据的方法。 Spring Boot是 Spring 的约定优于配置的解决方案,用于快速创建独立的生产级 Spring 应用程序。 JdbcTemplate是一个帮助程序员创建使用关系数据库和 JDBC 的应用程序的库。它处理许多繁琐且容易出错的低级细节,例如处理事务、清理资源和正确处理异常。
cars.sql
-- SQL for the Cars table START TRANSACTION; DROp TABLE IF EXISTS Cars; CREATE TABLE Cars(Id INTEGER PRIMARY KEY, Name VARCHAr(50), Price INTEGER); INSERT INTO Cars VALUES(1, 'Audi', 52642); INSERT INTO Cars VALUES(2, 'Mercedes', 57127); INSERT INTO Cars VALUES(3, 'Skoda', 9000); INSERT INTO Cars VALUES(4, 'Volvo', 29000); INSERT INTO Cars VALUES(5, 'Bentley', 350000); INSERT INTO Cars VALUES(6, 'Citroen', 21000); INSERT INTO Cars VALUES(7, 'Hummer', 41400); INSERT INTO Cars VALUES(8, 'Volkswagen', 21600); COMMIT;
在示例中,我们使用此表。
mysql> source cars.sql
命令行mysql工具可用于轻松创建表。您可以查看MySQL 教程 ,了解有关如何设置和使用 MySQL 数据库的更多信息。
控制台应用程序中的 HikariCP
在下面的示例中,我们使用 HikariCP 是一个 Java 控制台应用程序。
pom.xml4.0.0 com.zetcode HikariCPEx1.0-SNAPSHOT jar UTF-8 1.8 1.8 mysql mysql-connector-java5.1.40 com.zaxxer HikariCP2.5.1 org.slf4j slf4j-simple1.7.22 HikariCPEx
在 Maven 构建文件中,我们提供了 MySQL 驱动核心、HikariCP 收集池和slf4j-simple库的依赖项。(HikariCP 需要 slf4j)。
db.propertiesjdbcUrl=jdbc:mysql://localhost:3306/testdb?useSSL=false dataSource.user=testuser dataSource.password=test623 dataSource.cachePrepStmts=true dataSource.prepStmtCacheSize=250 dataSource.prepStmtCacheSqlLimit=2048
在db.properties文件中,我们有数据源的配置设置。该文件位于src/main/resources 目录中。
com/zetcode/HikariCPEx.javapackage com.zetcode;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class HikariCPEx {
public static void main(String[] args) {
String configFile = "src/main/resources/db.properties";
HikariConfig cfg = new HikariConfig(configFile);
HikariDataSource ds = new HikariDataSource(cfg);
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
try {
con = ds.getConnection();
pst = con.prepareStatement("SELECT * FROM Cars");
rs = pst.executeQuery();
while (rs.next()) {
System.out.format("%d %s %d %n", rs.getInt(1), rs.getString(2),
rs.getInt(3));
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(HikariCPEx.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
try {
if (rs != null) {
rs.close();
}
if (pst != null) {
pst.close();
}
if (con != null) {
con.close();
}
ds.close();
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(HikariCPEx.class.getName());
lgr.log(Level.WARNING, ex.getMessage(), ex);
}
}
}
}
该示例连接到 MySQL 数据库并从其 Cars表中选择所有汽车。
String configFile = "src/main/resources/db.properties"; HikariConfig cfg = new HikariConfig(configFile);
我们使用数据库属性创建一个HikariConfig对象,该对象用于创建数据源。
HikariDataSource ds = new HikariDataSource(cfg);
AHikariDataSource已创建。
con = ds.getConnection();
从数据源我们得到与 getConnection()方法的连接。
pst = con.prepareStatement("SELECt * FROM Cars");
rs = pst.executeQuery();
我们创建一个准备好的语句,一个预编译的语句,稍后使用该executeQuery()方法执行。
ds.close();
该close()方法关闭数据源及其关联的池。
Spring Boot 应用程序中的 HikariCP
在第二个应用程序中,我们在 Spring Boot 应用程序中使用 HikariCP。该应用程序是一个简单的 Spring Boot 控制台应用程序。
图:NetBeans 项目结构
该项目由六个文件组成:pom.xml、hikari.properties、 Car.java、Application.java、 MyRunner.java和 AppConfig.java.
pom.xml4.0.0 com.zetcode SpringBootHikariCP1.0-SNAPSHOT jar UTF-8 1.8 1.8 org.springframework.boot spring-boot-starter-parent1.4.3.RELEASE mysql mysql-connector-javaorg.springframework.boot spring-boot-starter-jdbcorg.springframework.boot spring-boot-startercom.zaxxer HikariCPSpringBootHikariCP
这是pom.xml文件。它包含 Spring Boot、MySQL 驱动程序和 HikariCP 的依赖项。Spring Boot 会自动处理日志记录依赖项。
com/zetcode/Car.javapackage com.zetcode.bean;
public class Car {
private Long Id;
private String name;
private int price;
public Long getId() {
return Id;
}
public void setId(Long Id) {
this.Id = Id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
@Override
public String toString() {
return "Car{" + "Id=" + Id + ", name=" +
name + ", price=" + price + '}';
}
}
这是一个简单的Carbean,它将映射到Cars表中的一行。
hikari.propertiesdriverClassName=com.mysql.jdbc.Driver jdbcUrl=jdbc:mysql://localhost:3306/testdb?useSSL=false maximumPoolSize=20 username=testuser password=test623 dataSource.cachePrepStmts=true dataSource.prepStmtCacheSize=250 dataSource.prepStmtCacheSqlLimit=2048
该hikari.properties文件位于src/main/resources 目录中,包含 HikariCP 配置选项。
com/zetcode/AppConfig.javapackage com.zetcode.conf;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean(destroyMethod = "close")
public DataSource dataSource() throws SQLException {
HikariConfig config = new HikariConfig("/hikari.properties");
HikariDataSource dataSource = new HikariDataSource(config);
return dataSource;
}
}
这AppConfig是一个设置 bean 的配置 bean HikariDataSource。@Bean注解表示一个方法生成一个由 Spring 容器管理的 bean 。
com/zetcode/Application.javapackage com.zetcode.client;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
@EnableAutoConfiguration
@ComponentScan(basePackages="com.zetcode")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
该类Application构建应用程序。@EnableAutoConfiguration注解启用 Spring Boot 自动配置。@ComponentScan注释告诉 Spring 在哪里寻找要创建的 bean 。
com/zetcode/MyRunner.javapackage com.zetcode.client;
import com.zetcode.bean.Car;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
@Component
public class MyRunner implements CommandLineRunner {
@Autowired
protected JdbcTemplate jtm;
@Override
public void run(String... args) throws Exception {
String sql = "SELECt * FROM Cars";
List cars = jtm.query(sql, new BeanPropertyRowMapper(Car.class));
cars.stream().forEach(System.out::println);
}
}
在MyRunner类中,我们注入JdbcTemplate对象并执行其query()方法。将BeanPropertyRowMapper 数据库表行映射到Carbean。
在本教程中,我们展示了如何在 Java 控制台和 Spring Boot 控制台应用程序中使用 HikariCP。



