测试druid中的监控功能

在yml配置文件中需要先要求使用Druid数据源

spring:
  datasource:
    username: root
    password: admin
    url: jdbc:mysql://localhost:3306/estore?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
    #在原有基础上,只需要指定type
    type: com.alibaba.druid.pool.DruidDataSource
	 #配置监控统计拦截的filters,stat:监控统计,log4j:日志记录,wall:防御sql注入
	filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
    

然后需要在config包下,写配置类DruidConfig

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 javax.xml.crypto.Data;
import java.util.HashMap;
//声明这是一个配置类
@Configuration
public class DruidConfig {
    //将刚才配置的yml文件和配置类绑定
    @ConfigurationProperties(prefix = "spring.datasource")
    //注入到Bean中,交给spring进行管理
    @Bean
    public DataSource druidDataSource(){
        return new DruidDataSource();
    }
    //后台监控功能
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
        //后台需要有人登录,账号密码配置
        HashMap<String, String> initParameters = new HashMap<>();
        //加配置
        //注意:参数名字是固定的,为loginUsername 和loginPassword
        initParameters.put("loginUsername","admin");
        initParameters.put("loginPassword","123456");

        //允许谁能访问
        initParameters.put("allow","");//value参数为空,所有人能访问

        //禁止谁能访问
//        initParameters.put("my","");//value为ip地址,配置了为拒绝访问

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

        return bean;
    }
}




上一篇:springboot整合Druid数据源[springboot8]


下一篇:instance和类型转换+面向对象三大特性:强调一下+static关键字详解 生成随机数方法