SpringBoot+Druid后台监控配置

  1. 导入依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-jdbc</artifactId>
       <version>2.4.0</version>
   </dependency>

   <!--Druid数据源-->
   <dependency>
       <groupId>com.alibaba</groupId>
       <artifactId>druid</artifactId>
       <version>1.2.6</version>
   </dependency>
   <dependency>
       <groupId>mysql</groupId>
       <artifactId>mysql-connector-java</artifactId>
</dependency>
  1. yml文件参数配置
spring:
  datasource:
    password: 123456
    username: root
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=Asia/Shanghai&amp;characterEncoding=utf-8&amp;useSSL=false
    type: com.alibaba.druid.pool.DruidDataSource	#指定数据源
  1. 连接测试
@SpringBootTest
public class MainApplicationTests {

    @Autowired
    DataSource dataSource;

    @Test
    public void bootTest(){
    //获取数据源信息	class com.alibaba.druid.pool.DruidDataSource
        System.out.println(dataSource.getClass());	
    }
}
  1. 编写配置类 Config
package com.boot.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import org.springframework.boot.context.properties.ConfigurationProperties;
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.util.HashMap;

@Configuration
public class DruidConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource(){
        return new DruidDataSource() ;
    }

    //后台监控
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");

        //后台登录设置
        HashMap<String,String> initParameters = new HashMap<>();
        initParameters.put("loginUsername","admine");   //loginUsername、loginUsername 是固定的
        initParameters.put("loginUsername","123456");

        //允许某个用户访问
        initParameters.put("allow","localhost");

        bean.setInitParameters(initParameters); //设置初始化参数

        return bean;
    }
    
    //设置一个拦截
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();

        bean.setFilter(new WebStatFilter());
        HashMap<String,String> initParameters = new HashMap<>();

        initParameters.put("exclusions","*.js,druid/*"); //哪些请求不拦截
        bean.setInitParameters(initParameters);
        return bean;

    }

}

  1. 启动登录:http://localhost:8080/druid
    SpringBoot+Druid后台监控配置
上一篇:springboot-data


下一篇:SpringBoot(三)JDBC+Durid(德鲁伊)