Spring Boot數據訪問-整合Druid數據源&Druid監控

前言

若是你沒有接觸過Spring Boot , 能夠看個人Spring Boot的系列文章: 點擊這裏php

開發環境

  • idea 2019.1css

  • mavenjava

  • Spring Boot 2.1.5mysql

  • jdk 1.8git

  • Win 10github

...web

主要依賴

使用 idea 自動化建立Spring Boot項目,這裏再也不贅述了, 不過須要注意的是, 咱們須要把Mysql驅動勾選上:spring

須要其餘依賴, 能夠本身勾選;sql

完整的pom文件:apache

<?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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.carson</groupId>
    <artifactId>spring-boot-06-data-jdbc</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-06-data-jdbc</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-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </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>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.16</version>
        </dependency>

      
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

複製代碼

記得把 druid 鏈接池添加上, 而且加上 log4j 的依賴, 不加的話等下會報錯

開始配置

而後個人配置文件選擇 yml 後綴的:

spring:
 datasource: 
 password: root
 username: root
 url: jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC
 driver-class-name: com.mysql.cj.jdbc.Driver
    # 指定鏈接池類型
 type: com.alibaba.druid.pool.DruidDataSource
# ------------分割線---------------------------
# 這下面的東西先不要添加到你的配置文件裏,由於不會生效
 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,去掉後監控界面sql沒法統計,'wall'用於防火牆
 filters: stat,wall,log4j
 maxPoolPreparedStatementPerConnectionSize: 20
 useGlobalDataSourceStat: true
 connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
複製代碼

從分割線如下的配置,是不會生效的, 因此咱們等下須要特殊配置一下,

不過讓咱們先測試一下咱們的鏈接池 是否爲 Druid 鏈接池,

打開咱們test包下的測試類, 我這裏放上個人完整代碼:

package com.carson.springboot;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.lang.model.element.VariableElement;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBoot06DataJdbcApplicationTests {

    @Autowired
    DataSource dataSource;

    @Test
    public void contextLoads() throws SQLException {
        System.out.println(dataSource.getClass());
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    }
}
複製代碼

運行此測試你將會看到控制檯輸出的鏈接池類型:

正是咱們須要的鏈接池類型

還記得剛纔說的不生效的那些配置嗎? 如今讓咱們來設置一下;

首先建立一個config配置類:

package com.carson.springboot.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 {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean 
    public DataSource druid() {
        return new DruidDataSource();
    }
}
複製代碼

@ConfigurationProperties: 前綴, 表示帶這些前綴的配置生效

而後在測試類打個斷點,debug運行一下:

結果:

能夠看到屬性是正確的

配置Druid監控

1) 配置一個管理後臺的Servlet

依然是剛纔的 DruidConfig 配置類,咱們來添加如下方法:

@Bean
    public ServletRegistrationBean statViewServlet() {
        ServletRegistrationBean bean = new ServletRegistrationBean          					(new StatViewServlet(), "/druid/*");
        
        Map<String, String> initParams = new HashMap<>();

        // 帳號,
        initParams.put("loginUsername", "admin");
        // 密碼,
        initParams.put("loginPassword", "123456");
        // 容許登陸的ip(爲空 就是全部都容許)
        initParams.put("allow", "");
        // 而後是不容許的ip地址
        initParams.put("deny", "192.123.11.11");
       	// 設置初始化參數
        bean.setInitParameters(initParams);
        return bean;
    }
複製代碼

這些參數是從哪裏來的呢? 就是下面:

2)配置一個監控的 filter

// 2)配置一個監控的 filter
    @Bean
    public FilterRegistrationBean webStatFilter() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
        
        Map<String, String> initParams = new HashMap<>();
        // 不攔截那些屬性
        initParams.put("exclusions","*.js,*.css,/druid/*");
		// 設置初始化參數
        bean.setInitParameters(initParams);
		// 默認攔截全部
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }
複製代碼

設置好這個,咱們能夠啓動Spring Boot的主類, 而後訪問 德魯伊(Druid)監視器: http://localhost:8080/druid

這個路徑是druid默認的路徑, 你會看到一個登陸頁面:

密碼就是咱們剛纔設置的 admin 和 123456

查看效果:

爲了查看如下咱們的 SQL監控 的效果, 咱們來寫一個 controller :

package com.carson.springboot.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;

import java.util.List;
import java.util.Map;

@Controller
public class HelloController {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @ResponseBody
    @GetMapping
    public Map<String, Object> map() {
        List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from user ");

        return list.get(0);
    }
}
複製代碼

而且向網頁發送 query 請求:

而後查看 SQL 監控:


END~~

相關文章
相關標籤/搜索