狂神說SpringBoot08:整合Druid

狂神說SpringBoot系列連載課程,通俗易懂,基於SpringBoot2.2.5版本,歡迎各位狂粉轉發關注學習。css

微信公衆號:狂神說(首發)    Bilibili:狂神說Java(視頻)html

未經做者受權,禁止轉載java

 集成Druid

Druid簡介

Java程序很大一部分要操做數據庫,爲了提升性能操做數據庫的時候,又不得不使用數據庫鏈接池。mysql

Druid 是阿里巴巴開源平臺上一個數據庫鏈接池實現,結合了 C3P0、DBCP 等 DB 池的優勢,同時加入了日誌監控。git

Druid 能夠很好的監控 DB 池鏈接和 SQL 的執行狀況,天生就是針對監控而生的 DB 鏈接池。程序員

Druid已經在阿里巴巴部署了超過600個應用,通過一年多生產環境大規模部署的嚴苛考驗。github

Spring Boot 2.0 以上默認使用 Hikari 數據源,能夠說 Hikari 與 Driud 都是當前 Java Web 上最優秀的數據源,咱們來重點介紹 Spring Boot 如何集成 Druid 數據源,如何實現數據庫監控。web

Github地址:https://github.com/alibaba/druid/spring

com.alibaba.druid.pool.DruidDataSource 基本配置參數以下:sql

 

 

 

配置數據源

一、添加上 Druid 數據源依賴。

<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.21</version>
</dependency>

二、切換數據源;以前已經說過 Spring Boot 2.0 以上默認使用 com.zaxxer.hikari.HikariDataSource 數據源,但能夠 經過 spring.datasource.type 指定數據源。

spring: datasource: username: root password: 123456 url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8 driver-class-name: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource # 自定義數據源

三、數據源切換以後,在測試類中注入 DataSource,而後獲取到它,輸出一看便知是否成功切換;

四、切換成功!既然切換成功,就能夠設置數據源鏈接初始化大小、最大鏈接數、等待時間、最小鏈接數 等設置項;能夠查看源碼

spring: datasource: username: root password: 123456 #?serverTimezone=UTC解決時區的報錯 url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8 driver-class-name: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource #Spring Boot 默認是不注入這些屬性值的,須要本身綁定 #druid 數據源專有配置 initialSize: 5 minIdle: 5 maxActive: 20 maxWait: 60000 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: SELECT 1 FROM DUAL testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true #配置監控統計攔截的filters,stat:監控統計、log4j:日誌記錄、wall:防護sql注入 #若是容許時報錯 java.lang.ClassNotFoundException: org.apache.log4j.Priority #則導入 log4j 依賴便可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j filters: stat,wall,log4j maxPoolPreparedStatementPerConnectionSize: 20 useGlobalDataSourceStat: true connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

五、導入Log4j 的依賴

<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

六、如今須要程序員本身爲 DruidDataSource 綁定全局配置文件中的參數,再添加到容器中,而再也不使用 Spring Boot 的自動生成了;咱們須要 本身添加 DruidDataSource 組件到容器中,並綁定屬性;

package com.kuang.config; import com.alibaba.druid.pool.DruidDataSource; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; @Configuration public class DruidConfig { /* 將自定義的 Druid數據源添加到容器中,再也不讓 Spring Boot 自動建立 綁定全局配置文件中的 druid 數據源屬性到 com.alibaba.druid.pool.DruidDataSource從而讓它們生效 @ConfigurationProperties(prefix = "spring.datasource"):做用就是將 全局配置文件中 前綴爲 spring.datasource的屬性值注入到 com.alibaba.druid.pool.DruidDataSource 的同名參數中 */ @ConfigurationProperties(prefix = "spring.datasource") @Bean public DataSource druidDataSource() { return new DruidDataSource(); } }

七、去測試類中測試一下;看是否成功!

@SpringBootTest class SpringbootDataJdbcApplicationTests { //DI注入數據源
 @Autowired DataSource dataSource; @Test public void contextLoads() throws SQLException { //看一下默認數據源
 System.out.println(dataSource.getClass()); //得到鏈接
        Connection connection = dataSource.getConnection(); System.out.println(connection); DruidDataSource druidDataSource = (DruidDataSource) dataSource; System.out.println("druidDataSource 數據源最大鏈接數:" + druidDataSource.getMaxActive()); System.out.println("druidDataSource 數據源初始化鏈接數:" + druidDataSource.getInitialSize()); //關閉鏈接
 connection.close(); } }

輸出結果 :可見配置參數已經生效!

 

配置Druid數據源監控

Druid 數據源具備監控的功能,並提供了一個 web 界面方便用戶查看,相似安裝 路由器 時,人家也提供了一個默認的 web 頁面。

因此第一步須要設置 Druid 的後臺管理頁面,好比 登陸帳號、密碼 等;配置後臺管理;

//配置 Druid 監控管理後臺的Servlet; //內置 Servlet 容器時沒有web.xml文件,因此使用 Spring Boot 的註冊 Servlet 方式
@Bean public ServletRegistrationBean statViewServlet() { ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*"); // 這些參數能夠在 com.alibaba.druid.support.http.StatViewServlet // 的父類 com.alibaba.druid.support.http.ResourceServlet 中找到
    Map<String, String> initParams = new HashMap<>(); initParams.put("loginUsername", "admin"); //後臺管理界面的登陸帳號
    initParams.put("loginPassword", "123456"); //後臺管理界面的登陸密碼 //後臺容許誰能夠訪問 //initParams.put("allow", "localhost"):表示只有本機能夠訪問 //initParams.put("allow", ""):爲空或者爲null時,表示容許全部訪問
    initParams.put("allow", ""); //deny:Druid 後臺拒絕誰訪問 //initParams.put("kuangshen", "192.168.1.20");表示禁止此ip訪問 //設置初始化參數
 bean.setInitParameters(initParams); return bean; }

配置完畢後,咱們能夠選擇訪問 :http://localhost:8080/druid/login.html

 進入以後

 配置 Druid web 監控 filter 過濾器

//配置 Druid 監控 之 web 監控的 filter //WebStatFilter:用於配置Web和Druid數據源之間的管理關聯監控統計
@Bean public FilterRegistrationBean webStatFilter() { FilterRegistrationBean bean = new FilterRegistrationBean(); bean.setFilter(new WebStatFilter()); //exclusions:設置哪些請求進行過濾排除掉,從而不進行統計
    Map<String, String> initParams = new HashMap<>(); initParams.put("exclusions", "*.js,*.css,/druid/*,/jdbc/*"); bean.setInitParameters(initParams); //"/*" 表示過濾全部請求
    bean.setUrlPatterns(Arrays.asList("/*")); return bean; }

平時在工做中,按需求進行配置便可,主要用做監控!

相關文章
相關標籤/搜索