Closed ldcsaa closed 1 year ago
原生配
原生配
原生配?什么意思呀,能简略讲讲么?
@ldcsaa 意思是通过spring来配置原生的servlet 和filter,以下是一个例子
/**
* Description
*
* @author alvinkwok
* @since 2023/10/17
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
/**
* @description 注册一个StatViewServlet,进行druid监控页面配置
* @return servlet registration bean
*/
@Bean
public ServletRegistrationBean<StatViewServlet> druidStatViewServlet() {
//先配置管理后台的servLet,访问的入口为/druid/
ServletRegistrationBean<StatViewServlet> servletRegistrationBean = new ServletRegistrationBean<>(
new StatViewServlet(), "/druid/*");
servletRegistrationBean.addInitParameter("loginUsername", "admin");
servletRegistrationBean.addInitParameter("loginPassword", "root");
servletRegistrationBean.addInitParameter("resetEnable", "false");
return servletRegistrationBean;
}
/**
* @description 注册一个过滤器,允许页面正常浏览
* @return filter registration bean
*/
@Bean
public FilterRegistrationBean<WebStatFilter> druidStatFilter(){
FilterRegistrationBean<WebStatFilter> filterRegistrationBean = new FilterRegistrationBean<>(
new WebStatFilter());
// 添加过滤规则.
filterRegistrationBean.addUrlPatterns("/*");
// 添加不需要忽略的格式信息.
filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
return filterRegistrationBean;
}
}
如果你使用的是动态做数据源刷新的情况,看下面的代码做相关filter配置,否则就直接配置在配置文件当中就行了。
@PostMapping("/add")
public Set<String> add(@RequestBody DataSourceDTO dto) {
DataSourceProperty dataSourceProperty = new DataSourceProperty();
BeanUtils.copyProperties(dto, dataSourceProperty);
// 配置druid的相关filter
DruidConfig druidConfig = new DruidConfig();
Map<String, Object> stat = new HashMap<>();
stat.put("setSlowSqlMillis", 30);
stat.put("setLogSlowSql", true);
stat.put("setMergeSql", true);
druidConfig.setStat(stat);
druidConfig.setFilters("stat");
dataSourceProperty.setDruid(druidConfig);
DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
DataSource dataSource = dataSourceCreator.createDataSource(dataSourceProperty);
ds.addDataSource(dto.getPoolName(), dataSource);
return ds.getDataSources().keySet();
}
@ldcsaa 以上的代码仅供参考,具体情况参考源码配置
以下配置无效,访问druid后台页面返回404