首頁 > 軟體

SpringBoot詳解如何進行整合Druid資料來源

2022-06-25 14:00:04

Druid是資料庫連線池,它能夠提供強大的監控和擴充套件功能。官方檔案

Spring Boot整合第三方技術的兩種方式:

  • 自定義
  • 找starter場景

1.自定義方式

使用自定義方式整合Druid

1.新增依賴

在pom.xml新增相關依賴

  <!--資料庫相關-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.6</version>
        </dependency>
    </dependencies>

2.編寫設定

application.properties

server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/db_springtest?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

設定Druid的監控頁功能:

Druid內建提供了一個StatViewServlet用於展示Druid的統計資訊。官方檔案 - 設定StatViewServlet

這個StatViewServlet的用途包括:

  • 提供監控資訊展示的html頁面
  • 提供監控資訊的JSON API

Druid內建提供一個StatFilter,用於統計監控資訊。官方檔案 - 設定_StatFilter

WebStatFilter用於採集web-jdbc關聯監控的資料,如SQL監控、URI監控。官方檔案 - 設定WebStatFilter

Druid提供了WallFilter,它是基於SQL語意分析來實現防禦SQL隱碼攻擊的。官方檔案 - 設定 wallfilter

DataSourceConfig

package com.limi.springboottest2.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Arrays;
@Configuration
public class DataSourceConfig {
    @Bean
    @ConfigurationProperties("spring.datasource")//複用組態檔的資料來源設定, 這樣就不用寫程式碼一個一個set了
    public DataSource dataSource() throws SQLException {
        DruidDataSource druidDataSource = new DruidDataSource();
        //加入監控和防火牆功能功能
        druidDataSource.setFilters("stat,wall");
        return druidDataSource;
    }
    /**
     * 設定 druid的監控頁功能
     * @return
     */
    @Bean
    public ServletRegistrationBean statViewServlet(){
        StatViewServlet statViewServlet = new StatViewServlet();
        ServletRegistrationBean<StatViewServlet> registrationBean =
                new ServletRegistrationBean<>(statViewServlet, "/druid/*");
        //監控頁賬號密碼:
        registrationBean.addInitParameter("loginUsername","admin");
        registrationBean.addInitParameter("loginPassword","123456");
        return registrationBean;
    }
    /**
     * WebStatFilter 用於採集web-jdbc關聯監控的資料。
     */
    @Bean
    public FilterRegistrationBean webStatFilter(){
        WebStatFilter webStatFilter = new WebStatFilter();
        FilterRegistrationBean<WebStatFilter> filterRegistrationBean = new FilterRegistrationBean<>(webStatFilter);
        filterRegistrationBean.setUrlPatterns(Arrays.asList("/*"));
        filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }
}

3.測試

HelloController

package com.limi.springboottest2.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @ResponseBody
    @GetMapping("/sql")
    public String test1(){
        String sql = "select count(*) from t_user";
        Long i = jdbcTemplate.queryForObject(sql, Long.class);
        return i.toString();
    }
}

多次點選重新整理進行存取

登入druid後臺檢視監控資訊

賬號admin, 密碼123456

2.starter方式(推薦)

使用場景啟動器整合druid, 效果和自定義方式一樣, 但更加方便

1.新增依賴

在pom.xml新增相關依賴

        <!--資料庫相關-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.17</version>
        </dependency>

pom.xml完整內容如下

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.limi</groupId>
    <artifactId>springboot-test2</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-test2</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <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>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <!--資料庫相關-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.17</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
            <!-- 下面外掛作用是工程打包時,不將spring-boot-configuration-processor打進包內,讓其只在編碼的時候有用 -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.springframework.boot</groupId>
                            <artifactId>spring-boot-configuration-processor</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

2.編寫設定

application.properties

server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/db_springtest?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

#監控SpringBean
spring.datasource.druid.aop-patterns=com.limi.springboottest2.*  
# 底層開啟功能,stat(sql監控),wall(防火牆)
spring.datasource.druid.filters=stat,wall

# 設定監控頁功能
spring.datasource.druid.stat-view-servlet.enabled=true
spring.datasource.druid.stat-view-servlet.login-username=admin
spring.datasource.druid.stat-view-servlet.login-password=123456
spring.datasource.druid.stat-view-servlet.reset-enable=false

# 監控web
spring.datasource.druid.web-stat-filter.enabled=true
spring.datasource.druid.web-stat-filter.url-pattern=/*
spring.datasource.druid.web-stat-filter.exclusions='*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'

# 對上面filters裡面的stat的詳細設定
spring.datasource.druid.filter.stat.slow-sql-millis=1000
spring.datasource.druid.filter.stat.log-slow-sql=true
spring.datasource.druid.filter.stat.enabled=true
spring.datasource.druid.filter.wall.enabled=true
spring.datasource.druid.filter.wall.config.drop-table-allow=false

3.測試

HelloController

package com.limi.springboottest2.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @ResponseBody
    @GetMapping("/sql")
    public String test1(){
        String sql = "select count(*) from t_user";
        Long i = jdbcTemplate.queryForObject(sql, Long.class);
        return i.toString();
    }
}

多次點選重新整理進行存取

登入druid後臺檢視監控資訊

賬號admin, 密碼123456

到此這篇關於SpringBoot詳解如何進行整合Druid資料來源的文章就介紹到這了,更多相關SpringBoot Druid資料來源內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com