package com.miyzh.config;

import com.alibaba.druid.filter.Filter;
import com.alibaba.druid.filter.stat.StatFilter;
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.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * description: DruidConfig
 * date: 2020/6/19 10:29
 * author: SZQ
 */
@Configuration
public class DruidConfig {
    @ConfigurationProperties(prefix = "spring.datasource")
    //加载时读取指定的配置信息,前缀为spring.datasource.druid
    @Bean
    public DataSource druid(){
        return new DruidDataSource();
    }
    //配置Druid的监控
//    1. 配置一个管理后台的servlet
//    @Bean
//    public ServletRegistrationBean statViewServlet() {
//        //创建servlet注册实体
//        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
//        //设置ip白名单
//        servletRegistrationBean.addInitParameter("allow", "192.168.0.1");
//        //设置ip黑名单，如果allow与deny共同存在时,deny优先于allow
//        //servletRegistrationBean.addInitParameter("deny","192.168.0.1");
//        //设置控制台管理用户
//        servletRegistrationBean.addInitParameter("loginUsername", "admin");
//        servletRegistrationBean.addInitParameter("loginPassword", "123456");
//        //是否可以重置数据
//        servletRegistrationBean.addInitParameter("resetEnable", "false");
//        return servletRegistrationBean;
//    }
//     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;
//    }
////     3. 配置druid连接池以及慢日志配置
//    @Bean
//    public Filter statFilter() {
//        StatFilter filter = new StatFilter();
//        filter.setSlowSqlMillis(5000);
//        filter.setLogSlowSql(true);
//        filter.setMergeSql(true);
//        return filter;
//    }
}
