首先肯定是引入druid的依赖:
com.alibaba druid 1.1.10
然后将druid配置到项目中:
在application.yml中加入
spring: datasource: type: com.alibaba.druid.pool.DruidDataSource ###数据源的其他配置 initialSize: 5 minIdle: 5 maxActive: 20 maxWait: 60000 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: SELECT 1 FROM DUAL testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true ### 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙 filters: stat,wall,log4j maxPoolPreparedStatementPerConnectionSize: 20 useGlobalDataSourceStat: true connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
这里配置好之后,数据源是从默认的tomcat.pool切换到了druid,可是druid的属性比如initialSize、minIdle还未生效,因为在DataSourceProperties.class下没有对应的匹配项,所以还需要我们手动配置:
新建DruidConfig.java
@Configurationpublic class DruidConfig { // 将所有前缀为spring.datasource下的配置项都加载到DataSource中 @ConfigurationProperties(prefix = "spring.datasource") @Bean public DataSource druidDataSource() { return new DruidDataSource(); }}
至此,Druid的所有配置都已完成,打断点可以看到配置已经生效:
最后,需要配置druid的监控页面
在上面的DruidConfig中加入代码:
@Bean public ServletRegistrationBean druidStatViewServlet() { ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*"); MapinitParams = new HashMap<>(); // 可配的属性都在 StatViewServlet 和其父类下 initParams.put("loginUsername", "admin-druid"); initParams.put("loginPassword", "111111"); servletRegistrationBean.setInitParameters(initParams); return servletRegistrationBean; } @Bean public FilterRegistrationBean druidWebStatFilter() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter()); Map initParams = new HashMap<>(); initParams.put("exclusions", "*.js,*.css,/druid/*"); filterRegistrationBean.setInitParameters(initParams); filterRegistrationBean.setUrlPatterns(Arrays.asList("/*")); return filterRegistrationBean; }
打开浏览器测试输入::8080/druid/login.html
可以看到
输入我们刚才在servlet中配置的账号密码就可以登录了