前面介绍了 Spring 怎样集成 C3P0,下面将通过一个简单示例演示 C3P0 和 Spring Boot 集成,然后通过 JdbcTemplate 从 MySQL 5.7.* 中获取数据库时间戳。
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>c3p0_spring_boot</artifactId> <version>0.0.1-SNAPSHOT</version> <name>c3p0_spring_boot</name> <description>Demo project for Spring Boot</description> <properties> <java.version>8</java.version> </properties> <dependencies> <!-- https://mvnrepository.com/artifact/c3p0/c3p0 --> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</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.c3p0_spring_boot.config; import com.mchange.v2.c3p0.ComboPooledDataSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.core.JdbcTemplate; import javax.sql.DataSource; /** * C3P0配置 * @author hxstrive.com */ @Configuration public class C3p0Config { /** * 配置 JdbcTemplate * @param dataSource 数据源 * @return */ @Bean public JdbcTemplate getJdbcTemplate(DataSource dataSource) { return new JdbcTemplate(dataSource); } /** * 配置数据源 * @return 返回 com.mchange.v2.c3p0.ComboPooledDataSource 数据源 */ @Bean public DataSource getDataSource() throws Exception { ComboPooledDataSource dataSource = new ComboPooledDataSource(); dataSource.setDriverClass("com.mysql.jdbc.Driver"); dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false"); dataSource.setUser("root"); dataSource.setPassword("aaaaaa"); // 连接初始化时创建的连接数 dataSource.setInitialPoolSize(3); // 连接池中拥有的最大连接数,如果获得新的连接时,连接总数已满,则不会再获取新连接,而是等待其他连接释放 dataSource.setMaxPoolSize(10); // 连接池保持的最小连接数 dataSource.setMinPoolSize(3); // 连接池在无空闲连接可用时一次性创建的新数据库连接数 dataSource.setAcquireIncrement(3); return dataSource; } }
Spring Boot 项目的启动类,代码如下:
package com.hxstrive.pool.c3p0_spring_boot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class C3p0SpringBootApplication { public static void main(String[] args) { SpringApplication.run(C3p0SpringBootApplication.class, args); } }
通过 @SpringBootTest 注解声明一个测试类,通过单元测试进行测试,代码如下:
package com.hxstrive.pool.c3p0_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 C3p0SpringBootApplicationTests { @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-04 13:25:47.075 INFO 13772 --- [ main] c.h.p.c.C3p0SpringBootApplicationTests : Starting C3p0SpringBootApplicationTests using Java 1.8.0_45 on hxstrive with PID 13772 (started by Administrator in D:\~my_workspace\jdbc_pool\c3p0_spring_boot) 2023-07-04 13:25:47.079 INFO 13772 --- [ main] c.h.p.c.C3p0SpringBootApplicationTests : No active profile set, falling back to 1 default profile: "default" 2023-07-04 13:25:49.356 INFO 13772 --- [ main] com.mchange.v2.log.MLog : MLog clients using java 1.4+ standard logging. 2023-07-04 13:25:50.223 INFO 13772 --- [ main] com.mchange.v2.c3p0.C3P0Registry : Initializing c3p0-0.9.1.2 [built 21-May-2007 15:04:56; debug? true; trace: 10] 2023-07-04 13:25:53.090 INFO 13772 --- [ main] c.h.p.c.C3p0SpringBootApplicationTests : Started C3p0SpringBootApplicationTests in 6.701 seconds (JVM running for 10.351) 2023-07-04 13:25:53.983 INFO 13772 --- [ main] c.m.v.c.i.AbstractPoolBackedDataSource : Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> 2va78sax8pac4kq046sf|3f36b447, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 2va78sax8pac4kq046sf|3f36b447, idleConnectionTestPeriod -> 0, initialPoolSize -> 3, jdbcUrl -> jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 10, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 3, numHelperThreads -> 3, numThreadsAwaitingCheckoutDefaultUser -> 0, preferredTestQuery -> null, properties -> {user=******, password=******}, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false ] 2023-07-04 13:25:54.0 Process finished with exit code 0