SpringBoot2.0默认是用hiraki数据库连接池,听说这个是当今运行效率最高的,但由于某些原因我要使用c3p0数据库连接池,所以就给大家说一下我的配置过程,其实还是挺简单的:

在pom.xml中加上依赖:

		<!-- 不使用默认的hikari数据库连接池,使用c3p0的 -->
		<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
		<dependency>
		    <groupId>com.mchange</groupId>
		    <artifactId>c3p0</artifactId>
		    <version>0.9.5.4</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/com.mchange/mchange-commons-java -->
		<dependency>
		    <groupId>com.mchange</groupId>
		    <artifactId>mchange-commons-java</artifactId>
		    <version>0.2.15</version>
		</dependency>

然后注释掉原来application.properties中的默认数据库配置而改用c3p0的:

#mysql
#spring.datasource.url=jdbc\:mysql\://localhost\:3306/test?useSSL\=false&characterEncoding\=utf8
#spring.datasource.username=test
#spring.datasource.password=test
#spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#spring.datasource.hikari.minimum-idle=10
#spring.datasource.hikari.maximum-pool-size=50

# c3p0
c3p0.jdbcUrl=jdbc:mysql://localhost:3306/test?autoReconnect=true&amp;autoReconnectForPools=true&amp;useUnicode=true&amp;characterEncoding=utf-8
c3p0.user=test
c3p0.password=test
c3p0.driverClass=com.mysql.jdbc.Driver
#c3p0.minPoolSize=2
#c3p0.maxPoolSize=100
#c3p0.maxIdleTime=0
#c3p0.acquireIncrement=3
#c3p0.maxStatements=1000
#c3p0.initialPoolSize=3
#c3p0.idleConnectionTestPeriod=60
#c3p0.acquireRetryAttempts=30
#c3p0.acquireRetryDelay=1000
#c3p0.breakAfterAcquireFailure=false
#c3p0.testConnectionOnCheckout=false

最后补充配置类:

package com.isuidian.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;

@Configuration
public class DataSourceConfiguration {
 
    // c3p0 连接池
    @Bean(name = "dataSource")
    @Qualifier(value = "dataSource")
    @Primary
    @ConfigurationProperties(prefix = "c3p0")
    public DataSource dataSource(@Autowired Environment environment) {
        return DataSourceBuilder.create().type(com.mchange.v2.c3p0.ComboPooledDataSource.class).build();
    }
}

搞掂,部署运行,在springboot的启动信息中可以看到c3p0已经生效了。