1. 程式人生 > >SpringBoot(七):集成DataSource 與 Druid監控配置

SpringBoot(七):集成DataSource 與 Druid監控配置

javax time max release too .repo select 進行 防火墻

綁定DataSource:Spring Boot默認的數據源是:org.apache.tomcat.jdbc.pool.DataSource,Druid是Java語言中最好的數據庫連接池,並且能夠提供強大的監控和擴展功能,而且datasource是一般項目都需要使用的功能。因此,這裏將學習如何使用springboot與druid集成datasource。

springboot2.0.1+alibaba druid組件導入maven:

1)導入alibaba druid組件:

        <!--druid 依賴-->
        <dependency>
<groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.9</version> </dependency>

備註:具體請查看官網提供的使用介紹:https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter

2)導入mysql驅動包:

        <!--MySQL Driver驅動包-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

3)導入springboot jpa集成組件:

        <!--
Spring Boot的JPA依賴包--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>

此時,pom.xml配置內容為:

技術分享圖片
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 4     <modelVersion>4.0.0</modelVersion>
 5 
 6     <groupId>com.dx</groupId>
 7     <artifactId>springboot-helloword</artifactId>
 8     <version>0.0.1-SNAPSHOT</version>
 9     <packaging>jar</packaging>
10 
11     <name>springboot-helloword</name>
12     <description>Demo project for Spring Boot</description>
13 
14     <parent>
15         <groupId>org.springframework.boot</groupId>
16         <artifactId>spring-boot-starter-parent</artifactId>
17         <version>2.0.1.RELEASE</version>
18         <relativePath/> <!-- lookup parent from repository -->
19     </parent>
20 
21     <properties>
22         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
23         <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
24         <java.version>1.8</java.version>
25     </properties>
26 
27     <dependencies>
28         <dependency>
29             <groupId>org.springframework.boot</groupId>
30             <artifactId>spring-boot-starter-web</artifactId>
31         </dependency>
32         <!--完成get set toString註冊 -->
33         <dependency>
34             <groupId>org.projectlombok</groupId>
35             <artifactId>lombok</artifactId>
36         </dependency>
37         <!--springboot 熱部署工具-->
38         <dependency>
39             <groupId>org.springframework.boot</groupId>
40             <artifactId>spring-boot-devtools</artifactId>
41             <optional>true</optional>
42         </dependency>
43         <dependency>
44             <groupId>org.springframework.boot</groupId>
45             <artifactId>spring-boot-starter-test</artifactId>
46             <scope>test</scope>
47         </dependency>
48         <dependency>
49             <groupId>org.springframework.boot</groupId>
50             <artifactId>spring-boot-starter-thymeleaf</artifactId>
51         </dependency>
52         <!--druid 依賴-->
53         <dependency>
54             <groupId>com.alibaba</groupId>
55             <artifactId>druid-spring-boot-starter</artifactId>
56             <version>1.1.9</version>
57         </dependency>
58         <!--MySQL Driver驅動包-->
59         <dependency>
60             <groupId>mysql</groupId>
61             <artifactId>mysql-connector-java</artifactId>
62             <scope>runtime</scope>
63         </dependency>
64         <!-- Spring Boot的JPA依賴包-->
65         <dependency>
66             <groupId>org.springframework.boot</groupId>
67             <artifactId>spring-boot-starter-data-jpa</artifactId>
68         </dependency>
69     </dependencies>
70 
71     <build>
72         <plugins>
73             <plugin>
74                 <groupId>org.springframework.boot</groupId>
75                 <artifactId>spring-boot-maven-plugin</artifactId>
76             </plugin>
77         </plugins>
78     </build>
79 
80 
81 </project>
View Code

自定義datasource配置項加載:

1)在src/resources/application.properties中添加以下配置信息:

# 自定義 數據庫配置信息
db.username=root
db.password=root
db.url=jdbc:mysql://localhost:3306/springboot_helloword
db.driver-class-name=com.mysql.jdbc.Driver

2)修改項目的啟動入口,添加DataSource的bean註入,及標註自定義參數配置註入:

package com.dx.controller;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;

@SpringBootApplication
public class SpringbootHellowordApplication {

    @Bean
    @ConfigurationProperties(prefix = "db")
    public DataSource dateSource() {
        DruidDataSource dataSource = new DruidDataSource();
        return dataSource;
    }

    public static void main(String[] args) {
        SpringApplication.run(SpringbootHellowordApplication.class, args);
    }
}

這裏的dateSource() 啟到的作用就是註入datasourcebean,同時加載自定義配置項的作用。

3)添加測試controller服務HelloWordController.java類:

package com.dx.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.sql.DataSource;
import java.sql.SQLException;

@Controller
public class HelloWordController {
    @Autowired
    private DataSource dataSource;

    @RequestMapping("/index")
    @ResponseBody
    public String index() throws SQLException {
        System.out.println(dataSource.getConnection());
        System.out.println(dataSource);
        return "hello spring boot";
    }
}

4)測試,在瀏覽器中訪問http://localhost:8888/index,查看控制臺打印信息:

com.mysql.jdbc.JDBC4Connection@7120165d
{
    CreateTime:"2018-04-09 20:41:41",
    ActiveCount:1,
    PoolingCount:0,
    CreateCount:1,
    DestroyCount:0,
    CloseCount:4,
    ConnectCount:5,
    Connections:[
    ]
}

使用springboot集成的datasource配置項:

1)修改datasource參數配置,使用系統集成參數配置項:

## 自定義 數據庫配置信息
#db.username=root
#db.password=root
#db.url=jdbc:mysql://localhost:3306/springboot_helloword
#db.driver-class-name=com.mysql.jdbc.Driver
#druid datasouce database settings begin
spring.datasource.druid.db-type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.driverClassName=com.mysql.jdbc.Driver
spring.datasource.druid.url=jdbc:mysql://localhost:3306/springboot_helloword?allowMultiQueries=true&autoReconnect=true&characterEncoding=utf-8
spring.datasource.druid.username=root
spring.datasource.druid.password=root
# 下面為連接池的補充設置,應用到上面所有數據源中
# 初始化大小,最小,最大
spring.datasource.druid.initial-size=5
spring.datasource.druid.min-idle=5
spring.datasource.druid.max-active=20
# 配置獲取連接等待超時的時間
spring.datasource.druid.max-wait=60000
# 配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接,單位是毫秒
spring.datasource.druid.time-between-eviction-runs-millis=60000
# 配置一個連接在池中最小生存的時間,單位是毫秒
spring.datasource.druid.min-evictable-idle-time-millis=300000
spring.datasource.druid.validation-query=SELECT 1 FROM DUAL
spring.datasource.druid.test-while-idle=true
spring.datasource.druid.test-on-borrow=false
spring.datasource.druid.test-on-return=false
# 打開PSCache,並且指定每個連接上PSCache的大小
spring.datasource.druid.pool-prepared-statements=true
spring.datasource.druid.max-pool-prepared-statement-per-connection-size=20
# 配置監控統計攔截的filters,去掉後監控界面sql無法統計,wall用於防火墻
spring.datasource.druid.filter.commons-log.connection-logger-name=stat,wall,log4j
spring.datasource.druid.filter.stat.log-slow-sql=true
spring.datasource.druid.filter.stat.slow-sql-millis=2000
# 通過connectProperties屬性來打開mergeSql功能;慢SQL記錄
spring.datasource.druid.connect-properties.=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合並多個DruidDataSource的監控數據
spring.datasource.druid.use-global-data-source-stat=true

2)在springboot服務啟動類不用註入其他bean和加載參數配置:

package com.dx.controller;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootHellowordApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootHellowordApplication.class, args);
    }
}

3)測試服務類HelloWordController.java與上邊一樣即可。

4)測試,在瀏覽器中訪問http://localhost:8888/index,查看控制臺打印信息:

com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl@3e6c29a1
{
    CreateTime:"2018-04-09 21:15:51",
    ActiveCount:1,
    PoolingCount:4,
    CreateCount:5,
    DestroyCount:0,
    CloseCount:4,
    ConnectCount:5,
    Connections:[
        {ID:1407373927, ConnectTime:"2018-04-09 21:15:51", UseCount:0, LastActiveTime:"2018-04-09 21:15:51"},
        {ID:485935020, ConnectTime:"2018-04-09 21:15:51", UseCount:0, LastActiveTime:"2018-04-09 21:15:51"},
        {ID:1400896839, ConnectTime:"2018-04-09 21:15:51", UseCount:0, LastActiveTime:"2018-04-09 21:15:51"},
        {ID:209844136, ConnectTime:"2018-04-09 21:15:51", UseCount:0, LastActiveTime:"2018-04-09 21:15:51"}
    ]
}

[
    {ID:1407373927,poolStatements:[]},
    {ID:485935020,poolStatements:[]},
    {ID:1400896839,poolStatements:[]},
    {ID:209844136,poolStatements:[]}
]

配置監控統計功能:

1)配置Servlet(監控視圖配置):

如下是在SpringBoot項目中基於註解的配置,如果是web.xml配置,按規則配置即可。

package com.base.servlet;

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

import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;

/**
 * druid數據源狀態監控.
 * */
@WebServlet(urlPatterns="/druid/*",
        initParams={
                @WebInitParam(name="allow",value="192.168.1.72,127.0.0.1"),// IP白名單(沒有配置或者為空,則允許所有訪問)
                @WebInitParam(name="deny",value="192.168.1.73"),// IP黑名單 (存在共同時,deny優先於allow)
                @WebInitParam(name="loginUsername",value="admin"),// 用戶名
                @WebInitParam(name="loginPassword",value="123456"),// 密碼
                @WebInitParam(name="resetEnable",value="false")// 禁用HTML頁面上的“Reset All”功能
        }
)
public class DruidStatViewServlet extends StatViewServlet {
    private static final long serialVersionUID = 1L;

}

2)過濾不需要監控的後綴:

package com.base.servlet;

import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;

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

/**
 * druid過濾器.
 */
@WebFilter(filterName = "druidWebStatFilter", urlPatterns = "/*",
        initParams = {
                @WebInitParam(name = "exclusions", value = "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")//忽略資源
        }
)
public class DruidStatFilter extends WebStatFilter {

}

3)測試配置是否成功。

訪問網址:http://localhost:8888/druid/index.html

技術分享圖片

一月份包含:
住宿票:4596(未報)
出差天數:2000=20*100(未報)
火車票:(三張:1578.5=520+538.5+520)(未報)
備註:三張火車票都在創世優聯

二月份包含:
住宿票:3596(未報)
出差天數:1300=13*100(未報)
火車票|飛機票|火車退票:1704.5=1080+86+538.5 (未報)
備註:
1)一張火車車票(2.26號的在老方手裏)
2)飛機票|退票發票(都在創世優聯)

三月份包含:
住宿票:8532=6296(2.26~3.19)+2236(3.21~4.4)(未報)
出差天數:3700=(22+15)*100(未報)
火車票:三張火車票538.5+538.5+431(未報)
備註:
1)一張火車車票(3.19號的在老方手裏)
2)其他兩張火車票(3.21號|4.4號的在我手裏)



SpringBoot(七):集成DataSource 與 Druid監控配置