springboot 整合阿里 Druid 資料庫連線池
阿新 • • 發佈:2018-12-22
一,Druid是什麼?
Druid是Java語言中最好的資料庫連線池。Druid能夠提供強大的監控和擴充套件功能。
二, 在哪裡下載druid
三, 怎麼獲取Druid的原始碼
Druid是一個開源專案,原始碼託管在github上,原始碼倉庫地址是 https://github.com/alibaba/druid。同時每次Druid釋出正式版本和快照的時候,都會把原始碼打包,你可以從上面的下載地址中找到相關版本的原始碼
四,springboot 整合 Druid 連線池
環境描述:springboot 2.0.4.RELEASE 與 jdk1.8
1,新建 springboot 專案:
File –> NEW –> Project –> 選擇Spring Initializr –> Next 輸入 maven grpup 和 Artifact
輸入後點擊 Next 選擇我們專案所需要的快速啟動maven依賴,如下圖:
隨後在點選 Next –> Finish
2,加入阿里系的Druid依賴包:
<!-- 阿里系的Druid依賴包 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId> druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
</dependency>
<!-- Druid 依賴 log4j包 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
3,在 application.properties 檔案中加入資料庫的配置:
#mysql 配置
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://192.168.2.126:3306/springboot_druid_demo?characterEncoding=utf-8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
#阿里druid連線池驅動配置資訊
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#連線池的配置資訊
#初始化大小,最小,最大
spring.datasource.initialSize=2
spring.datasource.minIdle=2
spring.datasource.maxActive=3
#配置獲取連線等待超時的時間
spring.datasource.maxWait=6000
#配置間隔多久才進行一次檢測,檢測需要關閉的空閒連線,單位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=60000
#配置一個連線在池中最小生存的時間,單位是毫秒
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
#開啟PSCache,並且指定每個連線上PSCache的大小
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
#配置監控統計攔截的filters,去掉後監控介面sql無法統計,'wall'用於防火牆
spring.datasource.filters=stat,wall,log4j
#通過connectProperties屬性來開啟mergeSql功能;慢SQL記錄
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
4,加入驅動配置類:
由於目前Spring Boot中預設支援的連線池只有 dbcp、dbcp2、 tomcat、hikari 連線池,Druid 暫時不在Spring Boot 中的直接支援,故需要進行配置資訊的定製:
新建druid包,加入DruidDBConfig 實現類
DruidDBConfig 類:
package springboot_druid_demo.druid;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
import java.sql.SQLException;
@Configuration
public class DruidDBConfig {
private static final Logger logger = LoggerFactory.getLogger(DruidDBConfig.class);
private static final String DB_PREFIX = "spring.datasource";
@Bean
public ServletRegistrationBean druidServlet() {
logger.info("init Druid Servlet Configuration ");
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
// IP白名單
servletRegistrationBean.addInitParameter("allow", "");
// IP黑名單(共同存在時,deny優先於allow)
servletRegistrationBean.addInitParameter("deny", "");
//控制檯管理使用者
servletRegistrationBean.addInitParameter("loginUsername", "");
servletRegistrationBean.addInitParameter("loginPassword", "");
//是否能夠重置資料 禁用HTML頁面上的“Reset All”功能
servletRegistrationBean.addInitParameter("resetEnable", "false");
return servletRegistrationBean;
}
@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
filterRegistrationBean.addUrlPatterns("/*");
filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
return filterRegistrationBean;
}
// 解決 spring.datasource.filters=stat,wall,log4j 無法正常註冊進去
@ConfigurationProperties(prefix = DB_PREFIX)
class IDataSourceProperties {
private String url;
private String username;
private String password;
private String driverClassName;
private int initialSize;
private int minIdle;
private int maxActive;
private int maxWait;
private int timeBetweenEvictionRunsMillis;
private int minEvictableIdleTimeMillis;
private String validationQuery;
private boolean testWhileIdle;
private boolean testOnBorrow;
private boolean testOnReturn;
private boolean poolPreparedStatements;
private int maxPoolPreparedStatementPerConnectionSize;
private String filters;
private String connectionProperties;
@Bean //宣告其為Bean例項
@Primary //在同樣的DataSource中,首先使用被標註的DataSource
public DataSource dataSource() {
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(url);
datasource.setUsername(username);
datasource.setPassword(password);
datasource.setDriverClassName(driverClassName);
//configuration
datasource.setInitialSize(initialSize);
datasource.setMinIdle(minIdle);
datasource.setMaxActive(maxActive);
datasource.setMaxWait(maxWait);
datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
datasource.setValidationQuery(validationQuery);
datasource.setTestWhileIdle(testWhileIdle);
datasource.setTestOnBorrow(testOnBorrow);
datasource.setTestOnReturn(testOnReturn);
datasource.setPoolPreparedStatements(poolPreparedStatements);
datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
try {
datasource.setFilters(filters);
} catch (SQLException e) {
System.err.println("druid configuration initialization filter: " + e);
}
datasource.setConnectionProperties(connectionProperties);
return datasource;
}
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 getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
public int getInitialSize() {
return initialSize;
}
public void setInitialSize(int initialSize) {
this.initialSize = initialSize;
}
public int getMinIdle() {
return minIdle;
}
public void setMinIdle(int minIdle) {
this.minIdle = minIdle;
}
public int getMaxActive() {
return maxActive;
}
public void setMaxActive(int maxActive) {
this.maxActive = maxActive;
}
public int getMaxWait() {
return maxWait;
}
public void setMaxWait(int maxWait) {
this.maxWait = maxWait;
}
public int getTimeBetweenEvictionRunsMillis() {
return timeBetweenEvictionRunsMillis;
}
public void setTimeBetweenEvictionRunsMillis(int timeBetweenEvictionRunsMillis) {
this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
}
public int getMinEvictableIdleTimeMillis() {
return minEvictableIdleTimeMillis;
}
public void setMinEvictableIdleTimeMillis(int minEvictableIdleTimeMillis) {
this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
}
public String getValidationQuery() {
return validationQuery;
}
public void setValidationQuery(String validationQuery) {
this.validationQuery = validationQuery;
}
public boolean isTestWhileIdle() {
return testWhileIdle;
}
public void setTestWhileIdle(boolean testWhileIdle) {
this.testWhileIdle = testWhileIdle;
}
public boolean isTestOnBorrow() {
return testOnBorrow;
}
public void setTestOnBorrow(boolean testOnBorrow) {
this.testOnBorrow = testOnBorrow;
}
public boolean isTestOnReturn() {
return testOnReturn;
}
public void setTestOnReturn(boolean testOnReturn) {
this.testOnReturn = testOnReturn;
}
public boolean isPoolPreparedStatements() {
return poolPreparedStatements;
}
public void setPoolPreparedStatements(boolean poolPreparedStatements) {
this.poolPreparedStatements = poolPreparedStatements;
}
public int getMaxPoolPreparedStatementPerConnectionSize() {
return maxPoolPreparedStatementPerConnectionSize;
}
public void setMaxPoolPreparedStatementPerConnectionSize(int maxPoolPreparedStatementPerConnectionSize) {
this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize;
}
public String getFilters() {
return filters;
}
public void setFilters(String filters) {
this.filters = filters;
}
public String getConnectionProperties() {
return connectionProperties;
}
public void setConnectionProperties(String connectionProperties) {
this.connectionProperties = connectionProperties;
}
}
}
加入 DruidDBConfig 類後 Druid 的配置資訊就算配置完成了,接下來加入model、service、mapper 測試 Druid 連線池的結果。
5,加入model、service、mapper 等類進行連線池測試:
User 類:
package springboot_druid_demo.model;
import lombok.Data;
@Data
public class User {
private Integer userId;
private String userName;
private String userPhone;
private String userAddress;
}
UserMapper 類:
package springboot_druid_demo.mappers;
import springboot_druid_demo.model.User;
public interface UserMapper {
int deleteByPrimaryKey(Integer var1);
int insertSelective(User var1);
User selectByPrimaryKey(Integer var1);
}
UserService 類:
package springboot_druid_demo.service;
import springboot_druid_demo.model.User;
public interface UserService {
int deleteByPrimaryKey(Integer var1);
int insertSelective(User var1);
User selectByPrimaryKey(Integer var1);
}
UserServiceImpl 類:
package springboot_druid_demo.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import springboot_druid_demo.mappers.UserMapper;
import springboot_druid_demo.model.User;
import springboot_druid_demo.service.UserService;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public int deleteByPrimaryKey(Integer var1) {
return userMapper.deleteByPrimaryKey(var1);
}
@Override
public int insertSelective(User var1) {
return userMapper.insertSelective(var1);
}
@Override
public User selectByPrimaryKey(Integer var1) {
return userMapper.selectByPrimaryKey(var1);
}
}
UserMapper.xml 檔案:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="springboot_druid_demo.mappers.UserMapper">
<delete id="deleteByPrimaryKey">
DELETE
FROM user
WHERE user_id = #{userId}
</delete>
<insert id="insertSelective">
INSERT INTO user (
user_name, user_phone, user_address
)
VALUES
(
#{userName}, #{userPhone}, #{userAddress}
)
</insert>
<resultMap id="selectByPrimaryKeyMap" type="springboot_druid_demo.model.User">
<result column="user_id" property="userId"/>
<result column="user_name" property="userName"/>
<result column="user_phone" property="userPhone"/>
<result column="user_address" property="userAddress"/>
</resultMap>
<select id="selectByPrimaryKey" parameterType="int" resultMap="selectByPrimaryKeyMap">
select *
from user
where user_id = #{userId}
</select>
</mapper>
6,以上類加入成功後還需要新增 mybatis 的一些配置:
- 在 application.properties 配置檔案中加入 mappers 的 xml 資料夾掃描配置:
#mapper檔案目錄
mybatis.mapper-locations=classpath*:mappers/*.xml
- 在 springboot 的 Application 啟動類中加入
@MapperScan("springboot_druid_demo.mappers") // 掃碼mapper包
9,安全設定:
如果需要加上登陸使用者密碼,只需要在上面程式碼
// 控制檯管理使用者
servletRegistrationBean.addInitParameter("loginUsername", "");
servletRegistrationBean.addInitParameter("loginPassword", "");
裡面填入自己的使用者名稱和密碼就可以了。