druid是阿里巴巴開源的資料庫連線池,提供了優秀的對資料庫操作的監控功能,本文要講解一下springboot專案怎麼整合druid。
本文在基於jpa的專案下開發,首先在pom檔案中額外加入druid依賴,pom檔案如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.dalaoyang</groupId>
<artifactId>springboot_druid</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot_druid</name>
<description>springboot_druid</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.12.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.28</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
複製程式碼
application.properties上半段和整合jpa一點沒變,下面加入了一些druid的配置,如果對druid的配置有什麼不理解的,可以去網上查一下。(這篇文章我覺得寫的很好,傳送門)
#埠號
server.port=8888
##validate 載入hibernate時,驗證建立資料庫表結構
##create 每次載入hibernate,重新建立資料庫表結構,這就是導致資料庫表資料丟失的原因。
##create-drop 載入hibernate時建立,退出是刪除表結構
##update 載入hibernate自動更新資料庫結構
##validate 啟動時驗證表的結構,不會建立表
##none 啟動時不做任何操作
spring.jpa.hibernate.ddl-auto=create
##控制檯列印sql
spring.jpa.show-sql=true
##資料庫配置
##資料庫地址
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false
##資料庫使用者名稱
spring.datasource.username=root
##資料庫密碼
spring.datasource.password=root
##資料庫驅動
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#這裡是不同的
#使用druid的話 需要多配置一個屬性spring.datasource.type
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# 連線池的配置資訊
# 初始化大小,最小,最大
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
# 配置獲取連線等待超時的時間
spring.datasource.maxWait=60000
# 配置間隔多久才進行一次檢測,檢測需要關閉的空閒連線,單位是毫秒
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記錄
複製程式碼
然後在專案中加入DruidConfig,簡單講解一下,這個配置檔案主要是載入application.properties的配置,程式碼如下:
package com.dalaoyang.config;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import com.alibaba.druid.pool.DruidDataSource;
/**
* @author dalaoyang
* @Description
* @project springboot_learn
* @package com.dalaoyang.config
* @email yangyang@dalaoyang.cn
* @date 2018/4/12
*/
@Configuration
public class DruidConfig {
private Logger logger = Logger.getLogger(this.getClass());
@Value("${spring.datasource.url}")
private String dbUrl;
@Value("${spring.datasource.username}")
private String username;
@Value("${spring.datasource.password}")
private String password;
@Value("${spring.datasource.driver-class-name}")
private String driverClassName;
@Value("${spring.datasource.initialSize}")
private int initialSize;
@Value("${spring.datasource.minIdle}")
private int minIdle;
@Value("${spring.datasource.maxActive}")
private int maxActive;
@Value("${spring.datasource.maxWait}")
private int maxWait;
@Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
private int timeBetweenEvictionRunsMillis;
@Value("${spring.datasource.minEvictableIdleTimeMillis}")
private int minEvictableIdleTimeMillis;
@Value("${spring.datasource.validationQuery}")
private String validationQuery;
@Value("${spring.datasource.testWhileIdle}")
private boolean testWhileIdle;
@Value("${spring.datasource.testOnBorrow}")
private boolean testOnBorrow;
@Value("${spring.datasource.testOnReturn}")
private boolean testOnReturn;
@Value("${spring.datasource.poolPreparedStatements}")
private boolean poolPreparedStatements;
@Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
private int maxPoolPreparedStatementPerConnectionSize;
@Value("${spring.datasource.filters}")
private String filters;
@Value("{spring.datasource.connectionProperties}")
private String connectionProperties;
@Bean
@Primary //主資料來源
public DataSource dataSource(){
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(this.dbUrl);
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) {
logger.error("druid configuration Exception", e);
}
datasource.setConnectionProperties(connectionProperties);
return datasource;
}
}
複製程式碼
然後建立DruidFilter,程式碼如下:
package com.dalaoyang.filter;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import com.alibaba.druid.support.http.WebStatFilter;
/**
* @author dalaoyang
* @Description
* @project springboot_learn
* @package com.dalaoyang.filter
* @email yangyang@dalaoyang.cn
* @date 2018/4/12
*/
@WebFilter(filterName="druidWebStatFilter",urlPatterns="/*",
initParams={
@WebInitParam(name="exclusions",value="*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")//忽略資源
}
)
public class DruidFilter extends WebStatFilter {
}
複製程式碼
新建DruidServlet,在類上面加註解@WebServlet,其中配置了登入druid監控頁面的賬號密碼,白名單黑名單之類的配置,程式碼如下:
package com.dalaoyang.servlet;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import com.alibaba.druid.support.http.StatViewServlet;
/**
* @author dalaoyang
* @Description
* @project springboot_learn
* @package com.dalaoyang.servlet
* @email yangyang@dalaoyang.cn
* @date 2018/4/12
*/
@WebServlet(urlPatterns="/druid/*",
initParams={
@WebInitParam(name="allow",value=""),// IP白名單(沒有配置或者為空,則允許所有訪問)
@WebInitParam(name="deny",value=""),// IP黑名單 (deny優先於allow)
@WebInitParam(name="loginUsername",value="admin"),// 登入druid管理頁面使用者名稱
@WebInitParam(name="loginPassword",value="admin")// 登入druid管理頁面密碼
})
public class DruidServlet extends StatViewServlet {
}
複製程式碼
然後在啟動類加入註解@ServletComponentScan,讓專案掃描到servlet,程式碼如下:
package com.dalaoyang;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
@SpringBootApplication
// 啟動類必須加入@ServletComponentScan註解,否則無法掃描到servlet
@ServletComponentScan
public class SpringbootDruidApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootDruidApplication.class, args);
}
}
複製程式碼
剩餘的就是和整合jpa一樣的entity(實體類),repository(資料操作層),controller(測試使用的controller),直接展示程式碼。
City
package com.dalaoyang.entity;
import javax.persistence.*;
/**
* @author dalaoyang
* @Description
* @project springboot_learn
* @package com.dalaoyang.Entity
* @email 397600342@qq.com
* @date 2018/4/7
*/
@Entity
@Table(name="city")
public class City {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int cityId;
private String cityName;
private String cityIntroduce;
public City(int cityId, String cityName, String cityIntroduce) {
this.cityId = cityId;
this.cityName = cityName;
this.cityIntroduce = cityIntroduce;
}
public City(String cityName, String cityIntroduce) {
this.cityName = cityName;
this.cityIntroduce = cityIntroduce;
}
public City() {
}
public int getCityId() {
return cityId;
}
public void setCityId(int cityId) {
this.cityId = cityId;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public String getCityIntroduce() {
return cityIntroduce;
}
public void setCityIntroduce(String cityIntroduce) {
this.cityIntroduce = cityIntroduce;
}
}
複製程式碼
CityRepository
package com.dalaoyang.repository;
import com.dalaoyang.entity.City;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* @author dalaoyang
* @Description
* @project springboot_learn
* @package com.dalaoyang.Repository
* @email 397600342@qq.com
* @date 2018/4/7
*/
public interface CityRepository extends JpaRepository<City,Integer> {
}
複製程式碼
CityController
package com.dalaoyang.controller;
import com.dalaoyang.entity.City;
import com.dalaoyang.repository.CityRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author dalaoyang
* @Description
* @project springboot_learn
* @package com.dalaoyang.controller
* @email 397600342@qq.com
* @date 2018/4/7
*/
@RestController
public class CityController {
@Autowired
private CityRepository cityRepository;
//http://localhost:8888/saveCity?cityName=北京&cityIntroduce=中國首都
@GetMapping(value = "saveCity")
public String saveCity(String cityName,String cityIntroduce){
City city = new City(cityName,cityIntroduce);
cityRepository.save(city);
return "success";
}
//http://localhost:8888/deleteCity?cityId=2
@GetMapping(value = "deleteCity")
public String deleteCity(int cityId){
cityRepository.delete(cityId);
return "success";
}
//http://localhost:8888/updateCity?cityId=3&cityName=瀋陽&cityIntroduce=遼寧省省會
@GetMapping(value = "updateCity")
public String updateCity(int cityId,String cityName,String cityIntroduce){
City city = new City(cityId,cityName,cityIntroduce);
cityRepository.save(city);
return "success";
}
//http://localhost:8888/getCityById?cityId=3
@GetMapping(value = "getCityById")
public City getCityById(int cityId){
City city = cityRepository.findOne(cityId);
return city;
}
}
複製程式碼
然後啟動專案,可以看到控制檯已經建立了city表。
然後訪問http://localhost:8888/druid,可以看到如下圖:
輸入賬號密碼admin,admin,如下圖
然後這時我們可以訪問http://localhost:8888/saveCity?cityName=北京&cityIntroduce=中國首都
然後點選導航上面的SQL監控,如下圖,
從上圖可以看到啟動專案建立表的sql已經剛剛執行的sql。到這裡整合已經完成了。
原始碼下載 :大老楊碼雲
個人網站:dalaoyang.cn