Use HikariCP connection pool in Spring Boot


Last time I helped Xiao Wang figure out how to use JDBC to connect to MySQL in Spring Boot, I have been waiting until he asked me the third question, such as how to use HikariCP connection pool in Spring Boot. But I waited for four days and didn't wait for any news. It seemed that he had disappeared from my world, and I was still intoxicated by the wonderful feeling of him slopping me.

Suddenly, I felt so empty in my days without Xiao Wang. How to do it? After much deliberation, it is better to write articles to survive. In the process of active creation, you may be able to get rid of the hard miss for Xiao Wang. What should I write?

After thinking about it, just write how to use HikariCP connection pool in Spring Boot. After all, in actual combat projects, JDBC must not be used, and connection pooling is a must. And HikariCP is said to be very fast, and it’s almost time that the default database connection pool of Spring Boot 2 has also been switched from Tomcat to HikariCP (can you change the stinky bug that likes the new and dislikes the old?).

The GitHub address of HikariCP is as follows:

https://github.com/brettwooldridge/HikariCP

The current star mark is 12K, and the number of uses has reached 43.1K. Let's take a look at its self-introduction.

It’s awesome. It turns out that Hikari comes from Japanese, meaning “light”. Does it mean as fast as the speed of light? To be honest, reading the profile feels as exciting and shocking as shaking hands with my goddess "Tang Wei".

Since Spring Boot 2 has used HikariCP by default, it is quite easy and comfortable to use, just a few simple steps.

01, initialize the MySQL database

Now that you want to connect to MySQL, you need to install the MySQL service on your computer (this article will skip it for now), and create the database and tables.

CREATE DATABASE `springbootdemo`;
DROP TABLE IF EXISTS `mysql_datasource`;
CREATE TABLE `mysql_datasource` (
  `id` varchar(64NOT NULL,
  PRIMARY KEY (`id`)
ENGINE=InnoDB DEFAULT CHARSET=utf8;

02. Use Spring Initlallzr to create a Spring Boot project

Creating a Spring Boot project is very simple, through Spring Initlallzr ( https://start.spring.io/ ).

Check the three dependencies of Web, JDBC, and MySQL Driver.

1) Web indicates that the project is a Web project, which is convenient for us to use URL directly.

3) MySQL Driver: the driver to connect to the MySQL server.

5) JDBC: Spring Boot 2 uses HikariCP by default, so HikariCP will add dependencies in spring-boot-starter-jdbc by default, so there is no need to actively add HikariCP dependencies.

PS: How to prove this? After the project is successfully imported, in the pom.xml file, press and hold the left mouse button + Ctrl key to access the spring-boot-starter-jdbc dependency node, and you can view the dependency information of HikariCP in the spring-boot-starter-jdbc.pom file .

After selecting the options, you can click the [Generate] button to generate an initialized Spring Boot project. What is generated is a compressed package, which needs to be decompressed when imported into the IDE.

03, edit the application.properties file

After the project is imported successfully, wait for Maven to download the dependencies, edit the application.properties file after completion, and configure the MySQL data source information.

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/springbootdemo?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456

Is there a feeling of deja vu (exactly the same as the data source configuration in [previous article]())? why? The answer has been told to everyone-default, default, default, and important things to say three times, Spring Boot 2 uses HikariCP connection pool by default.

04, edit Spring Boot project

In order for us to view the connection information of HikariCP, we edit the SpringBootMysqlApplication class and add the following content.

@SpringBootApplication
public class HikariCpDemoApplication implements CommandLineRunner {
    @Autowired
    private DataSource dataSource;

    public static void main(String[] args) {
        SpringApplication.run(HikariCpDemoApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        Connection conn = dataSource.getConnection();
        conn.close();
    }
}

HikariCpDemoApplication 实现了 CommandLineRunner 接口,该接口允许我们在项目启动的时候加载一些数据或者做一些事情,比如说我们尝试通过 DataSource 对象与数据源建立连接,这样就可以在日志信息中看到 HikariCP 的连接信息。CommandLineRunner 接口有一个方法需要实现,就是我们看到的 run() 方法。

通过 debug 的方式,我们可以看到,在项目运行的过程中,dataSource 这个 Bean 的类型为 HikariDataSource。

05、运行 Spring Boot 项目

接下来,我们直接运行 HikariCpDemoApplication 类,这样一个 Spring Boot 项目就启动成功了。

HikariDataSource 对象的连接信息会被打印出来。也就是说,HikariCP 连接池的配置启用了。快给自己点个赞。

06、为什么 Spring Boot 2.0 选择 HikariCP 作为默认数据库连接池

有几种基准测试结果可用来比较HikariCP和其他连接池框架(例如c3p0dbcp2tomcatvibur)的性能。例如,HikariCP团队发布了以下基准(可在此处获得原始结果):

HikariCP 团队为了证明自己性能最佳,特意找了几个背景对比了下。不幸充当背景的有 c3p0、dbcp2、tomcat 等传统的连接池。

从上图中,我们能感受出背景的尴尬,HikariCP 鹤立鸡群了。HikariCP 制作以如此优秀,原因大致有下面这些:

1)字节码级别上的优化:要求编译后的字节码最少,这样 CPU 缓存就可以加载更多的程序代码。

HikariCP 优化前的代码片段:

public final PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException
{
    return PROXY_FACTORY.getProxyPreparedStatement(this, delegate.prepareStatement(sql, columnNames));
}

HikariCP 优化后的代码片段:

public final PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException
{
    return ProxyFactory.getProxyPreparedStatement(this, delegate.prepareStatement(sql, columnNames));
}

以上两段代码的差别只有一处,就是 ProxyFactory 替代了 PROXY_FACTORY,这个改动后的字节码比优化前减少了 3 行指令。具体的分析参照 HikariCP 的 Wiki 文档

2)使用自定义的列表(FastStatementList)代替 ArrayList,可以避免 get() 的时候进行范围检查,remove() 的时候从头到尾的扫描。

https://github.com/itwanger/JavaBooks

Guess you like

Origin blog.51cto.com/2324584/2543254