HikariCP 与 Spring Boot 集成

前面介绍了 Spring 怎样集成 HikariCP,下面将通过一个简单示例演示 HikariCP 和 Spring Boot 集成,然后通过 JdbcTemplate 从 MySQL 5.7.* 中获取数据库时间戳。

Maven 依赖

Spring Boot 项目的依赖如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-parent</artifactId>
       <version>2.7.13</version>
       <relativePath/> <!-- lookup parent from repository -->
   </parent>
   <groupId>com.hxstrive.jdbc_pool</groupId>
   <artifactId>HikariCP_spring_boot</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>HikariCP_spring_boot</name>
   <description>Demo project for Spring Boot</description>

   <properties>
       <java.version>8</java.version>
   </properties>

   <dependencies>
       <!-- https://mvnrepository.com/artifact/com.zaxxer/HikariCP -->
       <dependency>
           <groupId>com.zaxxer</groupId>
           <artifactId>HikariCP</artifactId>
           <version>4.0.3</version>
       </dependency>

       <!-- MySQL 驱动依赖 -->
       <dependency>
           <groupId>mysql</groupId>
           <artifactId>mysql-connector-java</artifactId>
           <version>5.1.38</version>
       </dependency>

       <!-- Spring Boot JDBC依赖驱动 -->
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-jdbc</artifactId>
       </dependency>

       <!-- Spring Boot Web 驱动依赖 -->
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-web</artifactId>
       </dependency>

       <!-- Spring Boot 开发和测试依赖 -->
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-devtools</artifactId>
           <scope>runtime</scope>
           <optional>true</optional>
       </dependency>
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-test</artifactId>
           <scope>test</scope>
       </dependency>
   </dependencies>

   <build>
       <plugins>
           <plugin>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-maven-plugin</artifactId>
               <configuration>
                   <excludes>
                       <exclude>
                           <groupId>org.projectlombok</groupId>
                           <artifactId>lombok</artifactId>
                       </exclude>
                   </excludes>
               </configuration>
           </plugin>
       </plugins>
   </build>

</project>

配置类

使用 @Configuration 声明一个配置类,配置 JdbcTemplate 和 DataSource(数据源),代码如下:

package com.hxstrive.pool.HikariCP_spring_boot.config;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;

/**
* HikariCP配置
* @author hxstrive.com
*/
@Configuration
public class HikariCPConfig {

   /**
    * 配置 JdbcTemplate
    * @param dataSource 数据源
    * @return
    */
   @Bean
   public JdbcTemplate getJdbcTemplate(DataSource dataSource) {
       return new JdbcTemplate(dataSource);
   }

   /**
    * 配置数据源
    * @return 返回 com.zaxxer.hikari.HikariDataSource 数据源
    */
   @Bean
   public DataSource getDataSource() throws Exception {
       HikariConfig config = new HikariConfig();
       config.setDriverClassName("com.mysql.jdbc.Driver");
       config.setJdbcUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false");
       config.setUsername("root");
       config.setPassword("aaaaaa");
       config.addDataSourceProperty("cachePrepstmts", "true");
       config.addDataSourceProperty("prepstmtCachesize", "250");
       config.addDataSourceProperty("prepstmtCacheSqlLimit", "2048");
       return new HikariDataSource(config);
   }

}

入口类

Spring Boot 项目的启动类,代码如下:

package com.hxstrive.pool.HikariCP_spring_boot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class HikariCPSpringBootApplication {

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

}

测试类

通过 @SpringBootTest 注解声明一个测试类,通过单元测试进行测试,代码如下:

package com.hxstrive.pool.HikariCP_spring_boot;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import java.sql.Timestamp;

@SpringBootTest
class HikariCPSpringBootApplicationTests {

   @Autowired
   private JdbcTemplate jdbcTemplate;

   @Test
   void contextLoads() {
       // 获取数据库当前的时间戳
       Timestamp ts = jdbcTemplate.queryForObject("select CURRENT_TIMESTAMP() as ct", Timestamp.class);
       System.out.println(ts);
   }

}

运行测试类,输出如下:

... 省略 ...
 .   ____          _            __ _ _
/\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/  ___)| |_)| | | | | || (_| |  ) ) ) )
 '  |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot ::               (v2.7.13)

2023-07-11 12:42:44.037  INFO 8296 --- [           main] c.h.p.d.DruidSpringBootApplicationTests  : Starting DruidSpringBootApplicationTests using Java 1.8.0_45 on hxstrive with PID 8296 (started by Administrator in D:\~my_workspace\jdbc_pool\druid_spring_boot)
2023-07-11 12:42:44.040  INFO 8296 --- [           main] c.h.p.d.DruidSpringBootApplicationTests  : No active profile set, falling back to 1 default profile: "default"
2023-07-11 12:42:49.465  INFO 8296 --- [           main] c.h.p.d.DruidSpringBootApplicationTests  : Started DruidSpringBootApplicationTests in 6.406 seconds (JVM running for 11.577)
2023-07-11 12:42:51.004  INFO 8296 --- [           main] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} inited
2023-07-11 12:42:51.0
2023-07-11 12:42:51.093  INFO 8296 --- [ionShutdownHook] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} closing ...
2023-07-11 12:42:51.101  INFO 8296 --- [ionShutdownHook] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} closed
说说我的看法
全部评论(
没有评论
关于
本网站专注于 Java、数据库(MySQL、Oracle)、Linux、软件架构及大数据等多领域技术知识分享。涵盖丰富的原创与精选技术文章,助力技术传播与交流。无论是技术新手渴望入门,还是资深开发者寻求进阶,这里都能为您提供深度见解与实用经验,让复杂编码变得轻松易懂,携手共赴技术提升新高度。如有侵权,请来信告知:hxstrive@outlook.com
公众号