SpringBoot集成阿裏巴巴Druid監控
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 [email protected] * @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 [email protected]
* @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 [email protected]
* @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 [email protected]
* @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 [email protected]
* @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 [email protected]
* @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。到這裏整合已經完成了。
源碼下載 :大老楊碼雲
個人網站:https://dalaoyang.cn
SpringBoot集成阿裏巴巴Druid監控