package com.corewing.app.config;

import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
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 java.util.HashMap;
import java.util.Map;

/**
 * Druid 监控配置类
 */
@Configuration
public class DruidConfig {

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

        Map<String, String> initParams = new HashMap<>();
        // 监控页面登录用户名
        initParams.put("loginUsername", "admin");
        // 监控页面登录密码
        initParams.put("loginPassword", "admin123");
        // 允许访问的IP，默认允许所有
        initParams.put("allow", "");
        // 禁止访问的IP
        initParams.put("deny", "");
        // 禁用HTML页面上的"Reset All"功能
        initParams.put("resetEnable", "false");

        bean.setInitParameters(initParams);
        return bean;
    }

    /**
     * 配置 Druid Web 监控 Filter
     */
    @Bean
    public FilterRegistrationBean<WebStatFilter> webStatFilter() {
        FilterRegistrationBean<WebStatFilter> bean = new FilterRegistrationBean<>();
        bean.setFilter(new WebStatFilter());

        Map<String, String> initParams = new HashMap<>();
        // 排除不需要监控的资源
        initParams.put("exclusions", "*.js,*.css,*.gif,*.jpg,*.png,*.ico,/druid/*");

        bean.setInitParameters(initParams);
        // 拦截所有请求
        bean.addUrlPatterns("/*");

        return bean;
    }
}
