springboot2.1.7整合Druid

Posted 哎哟我去a

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot2.1.7整合Druid相关的知识,希望对你有一定的参考价值。

一、maven的依赖;文中就贴重点的, 其他依赖就不贴了

  

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

二、yml的配置

  

spring:
  application:
    name: Druids
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3308/systems?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai 
    username: root 
    password: 123456
    initialSize: 50 
    maxActive: 50 
    validationQuery: select DATE_SUB(curdate(),INTERVAL 0 DAY)
    filters:   stat,wall,log4j  

三、java配置类

  

import org.springframework.context.annotation.Configuration;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
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;

@Configuration
public class DruidConfiguration {
    
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druid(){
       return  new DruidDataSource();
    }

    //配置Druid的监控
    //1、配置一个管理后台的Servlet
    @Bean
    public ServletRegistrationBean<StatViewServlet> statViewServlet(){
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<StatViewServlet>(new StatViewServlet(), "/druid/*");
        Map<String,String> initParams = new HashMap<>();

        initParams.put("loginUsername","admin");
        initParams.put("loginPassword","123456");
        initParams.put("allow","");//默认就是允许所有访问
       // initParams.put("deny","192.168.15.21");

        bean.setInitParameters(initParams);
        return bean;
    }


    //2、配置一个web监控的filter
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @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;
    }
     
}

最后一步来测试:

  

 

 

以上是关于springboot2.1.7整合Druid的主要内容,如果未能解决你的问题,请参考以下文章

springboot2.1.7整合mybatis

SpringBoot整合Druid数据连接池

springboot整合dubbo

springboot整合Druid数据源

java 整合redis缓存 SSM 后台框架 rest接口 shiro druid maven b

java 整合redis缓存 SSM 后台框架 rest接口 shiro druid maven b