Druid是Java语言中最好的数据库连接池。Druid能够提供强大的监控和扩展功能。考虑到可能是数据库连接的问题,所以我打算引入其他的数据池,引入数据池的时候找来找去,比较了当前两个最火的数据池,druid和HikariCP,比来比去选了阿里的druid,虽然spring boot默认不支持druid,而是支持HikariCP,而且HikariCP的性能更好,但是阿里功能多,界面友好方便,性价比更高!
配置
首先呢引入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
然后呢在yml中配置
druid:
driver-class: com.mysql.jdbc.Driver
min-idle: 1
password: 123456
test-on-borrow: true
timeBetweenEvictionRunsMillis: 9000
max-active: 20
initial-size: 1
url: jdbc:mysql://192.168.8.100:3306/test?useUnicode=true&characterEncoding=utf8
username: root
自定义配置有助于更好的维护
再然后呢是或者配置类
package com.maoxs.conf;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "druid")
public class DruidProperties {
private String url;
private String username;
private String password;
private String driverClass;
private int maxActive;
private int minIdle;
private int initialSize;
private boolean testOnBorrow;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDriverClass() {
return driverClass;
}
public void setDriverClass(String driverClass) {
this.driverClass = driverClass;
}
public int getMaxActive() {
return maxActive;
}
public void setMaxActive(int maxActive) {
this.maxActive = maxActive;
}
public int getMinIdle() {
return minIdle;
}
public void setMinIdle(int minIdle) {
this.minIdle = minIdle;
}
public int getInitialSize() {
return initialSize;
}
public void setInitialSize(int initialSize) {
this.initialSize = initialSize;
}
public boolean isTestOnBorrow() {
return testOnBorrow;
}
public void setTestOnBorrow(boolean testOnBorrow) {
this.testOnBorrow = testOnBorrow;
}
}
再然后呢就是注入我们的数据源
package com.maoxs.conf;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass