spring boot 配置数据源
第一种使用DriverManagerDataSource
@Configuration
public class GlobalConfig {
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUsername("root");
dataSource.setPassword("root");
dataSource.setUrl("jdbc:mysql://localhost/test");
return dataSource;
}
}
第二种 使用配置文件
@Configuration
public class GlobalConfig {
@Bean
@ConfigurationProperties("app.datasource")
public DataSource dataSource(){
return DataSourceBuilder.create().build();
}
}
在application.properties中添加:
app.datasource.url=jdbc:mysql://localhost/test
app.datasource.username=root
app.datasource.password=root
app.datasource.driverClassName=com.mysql.jdbc.Driver
第三种 直接使用数据连接池c3p0
@Configuration public class GlobalConfig { @Bean @ConfigurationProperties("c3p0") public DataSource dataSource(){ return DataSourceBuilder.create().type(com.mchange.v2.c3p0.ComboPooledDataSource.class).build(); } }
在application.properties中添加:
c3p0.jdbcUrl=jdbc:mysql://127.0.0.1:3306/test
c3p0.user=root
c3p0.password=root
c3p0.driverClass=com.mysql.jdbc.Driver
c3p0.minPoolSize=5
c3p0.maxPoolSize=20
c3p0.initialPoolSize=8
c3p0.maxIdleTime=120
c3p0.acquireIncrement=3
c3p0.maxStatements=100
c3p0.idleConnectionTestPeriod=60
c3p0.acquireRetryAttempts=30
c3p0.acquireRetryDelay=1000
c3p0.breakAfterAcquireFailure=false
c3p0.testConnectionOnCheckout=false
minPoolSize 连接池中最小连接数
maxPoolSize 连接池中最大连接数
initialPoolSize 初始化连接数
maxIdleTime 最大空闲时间,超时连接被丢弃
acquireIncrement 连接池中连接耗尽时,一次获取的连接数