引入maven依賴
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.21</version>
</dependency>
編寫數據源配置文件
將配置文件放在項目根路徑下
driverClassName = com.mysql.jdbc.Driver
url = jdbc:mysql://domain/database
username = database-username
password = database-password
initialSize = 2
maxActive = 60
minIdle = 3
maxWait = 60000
removeAbandoned = true
removeAbandonedTimeout = 180
timeBetweenEvictionRunsMillis = 60000
minEvictableIdleTimeMillis = 300000
validationQuery = SELECT 1 FROM DUAL
testWhileIdle = true
testOnBorrow = false
testOnReturn = false
poolPreparedStatements = true
maxPoolPreparedStatementPerConnectionSize = 50
filters = stat
獲取數據源對象
public class DBService {
private DataSource dataSource;
public DBService() throws Exception{
InputStream resourceAsStream = DBService.class.getClassLoader().getResourceAsStream("db.properties");
Properties prop = new Properties();
prop.load(resourceAsStream);
DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
this.dataSource = dataSource;
}
}