實際項目(SpringBoot項目)中集成Druid實現監控功能

參考網頁

https://blog.csdn.net/liuchuanhong1/article/details/55050131css

https://blog.csdn.net/CoffeeAndIce/article/details/78707819html

https://www.pocketdigi.com/20170530/1577.htmljava

爲什麼要集成Druid

性能

    官方數據Benchmark_aliyun,druid在響應時間上優於其餘幾個線程池。非官方的測試數據可能差距沒這麼明顯,但仍然高於其餘幾個線程池。web

自帶監控功能

    自帶監控,可幫助開發者找出慢查詢,查看併發數等。spring

步驟1--pom文件中加入Druid依賴

<!-- ==========集成Druid start==========-->

<dependency>

<groupId>com.alibaba</groupId>

<artifactId>druid</artifactId>

<version>1.0.31</version>

</dependency>

<!-- ==========集成Druid end==========-->

 

步驟2--在application.properties配置文件中加入druid配置

############################################# Druid參數

# 初始化大小,最小,最大  

spring.datasource.initialSize=5  

spring.datasource.minIdle=5  

spring.datasource.maxActive=20  

# 配置獲取鏈接等待超時的時間  

spring.datasource.maxWait=60000  

# 配置間隔多久才進行一次檢測,檢測須要關閉的空閒鏈接,單位是毫秒  

spring.datasource.timeBetweenEvictionRunsMillis=60000  

# 配置一個鏈接在池中最小生存的時間,單位是毫秒  

spring.datasource.minEvictableIdleTimeMillis=300000  

# 校驗SQL,Oracle配置 spring.datasource.validationQuery=SELECT 1 FROM DUAL,若是不配validationQuery項,則下面三項配置無用  

spring.datasource.validationQuery=SELECT 'x'  

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  

# 合併多個DruidDataSource的監控數據  

spring.datasource.useGlobalDataSourceStat=true

 

步驟3--配置WebFilter【過濾不須要監控的後綴】

package com.richfit.ruiche.common.druidConfig;


import javax.servlet.annotation.WebFilter;  

import javax.servlet.annotation.WebInitParam;  

  

import com.alibaba.druid.support.http.WebStatFilter;  

  

@WebFilter(filterName="druidStatFilter",urlPatterns="/*",  

initParams={  

        @WebInitParam(name="exclusions",value="*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")// 忽略資源  

})  

public class DruidStatFilter extends WebStatFilter {  

  

}

 

步驟4--配置WebServlet【監控視圖配置】

package com.richfit.ruiche.common.druidConfig;


import javax.servlet.annotation.WebInitParam;  

import javax.servlet.annotation.WebServlet;  

  

import com.alibaba.druid.support.http.StatViewServlet;  

  

@WebServlet(urlPatterns = "/druid/*",  

initParams={  

        @WebInitParam(name="allow",value=""),// IP白名單 (沒有配置或者爲空,則容許全部訪問)  

//        @WebInitParam(name="deny",value="192.168.0.0"),// IP黑名單 (存在共同時,deny優先於allow)  

        @WebInitParam(name="loginUsername",value="admin"),// druid監控頁面登錄用戶名  

        @WebInitParam(name="loginPassword",value="admin"),// druid監控頁面登錄密碼  

        @WebInitParam(name="resetEnable",value="false")// 禁用HTML頁面上的「Reset All」功能  

})  

public class DruidStatViewServlet extends StatViewServlet {  

  

    /**  

     *   

     */  

    private static final long serialVersionUID = 1L;  

  

}

步驟5--不使用spring boot自動配置功能,手動初始化DataSource

package com.richfit.ruiche.common.druidConfig;


import java.sql.SQLException;  


import javax.sql.DataSource;  

  

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;  

  

/**

 *  

 * 描述:若是不使用代碼手動初始化DataSource的話,監控界面的SQL監控會沒有數據("是spring boot的bug???")

 * @author chhliu 

 * 建立時間:2017年2月9日 下午10:33:08

 * @version 1.2.0

 */  

@Configuration  

public class DruidConfiguration {  

    @Value("${spring.datasource.url}")  

    private String dbUrl;  

    @Value("${spring.datasource.username}")  

    private String username;  

    @Value("${spring.datasource.password}")  

    private String password;  

//    @Value("${spring.datasource.driverClassName}")  

    @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;  

    @Value("${spring.datasource.useGlobalDataSourceStat}")  

    private boolean useGlobalDataSourceStat;  

  

    @Bean     //聲明其爲Bean實例  

    @Primary  //在一樣的DataSource中,首先使用被標註的DataSource  

    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);  

        datasource.setUseGlobalDataSourceStat(useGlobalDataSourceStat);  

        try {  

            datasource.setFilters(filters);  

        } catch (SQLException e) {  

            System.err.println("druid configuration initialization filter: "+ e);  

        }  

        datasource.setConnectionProperties(connectionProperties);  

        return datasource;  

    }  

}

 

步驟6--主啓動類上設置掃描Servlet

package com.richfit.ruiche;


import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.boot.context.properties.EnableConfigurationProperties;

import org.springframework.boot.web.servlet.ServletComponentScan;

import org.springframework.scheduling.annotation.EnableAsync;

import org.springframework.scheduling.annotation.EnableScheduling;


import com.richfit.ruiche.common.globalSetting.RunEnvSetting;

import com.richfit.ruiche.framework.threadPool.TaskThreadPoolConfig;

import com.richfit.ruiche.util.EMailConfig;




//@SpringBootApplication(exclude = SpringDataWebAutoConfiguration.class)

//@EnableConfigurationProperties({EMailConfig.class,SSLEMailConfig.class,WebVersion.class})



@SpringBootApplication

@EnableConfigurationProperties({EMailConfig.class,RunEnvSetting.class,TaskThreadPoolConfig.class})  

//@RestController

//@Configuration  

//@ComponentScan(basePackages = "com.richfit.ruiche")

//@EnableAutoConfiguration

@EnableScheduling

//@EnableCaching

//開啓對異步任務的支持

@EnableAsync

//注意要加上@ServletComponentScan註解,不然Servlet沒法生效 -----Druid監控

@ServletComponentScan

public class RichfitCBMRest {

    public static void main(String[] args) {

        SpringApplication.run(RichfitCBMRest.class, args);

        

   //打印系統中定義的服務類     

// ApplicationContext ctx = SpringApplication.run(RichfitCBMRest.class,

// args);

// String[] beanNames = ctx.getBeanNamesForAnnotation(Service.class);

// System.out.println("Service註解beanNames個數:" + beanNames.length);

//

// for (String bn : beanNames) {

// System.out.println(bn);

// }

//

// System.out.println("打印結束");

    }

}

測試

監控頁面登陸地址

http://localhost:1008/druid/login.htmlsql

Sql監控

能夠看到sql監控頁面已經監控到sql語句併發

Uri監控

Uri監控頁面,能夠看到監控到了剛纔訪問的uri地址:app

/LoginService/login異步

相關文章
相關標籤/搜索