1.导入Druid依赖
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.21</version> </dependency>
2.编写application.yml配置文件
spring: datasource: username: xxx password: xxx url: jdbc:mysql://localhost:3306/数据库名?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true driver-class-name: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource #Spring Boot 默认是不注入这些属性值的,需要自己绑定 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,stat:监控统计、log4j:日志记录、wall:防御sql注入 #如果允许时报错 java.lang.ClassNotFoundException:org.apache.log4j.Priority #则导入 log4j 依赖即可 filters: stat,wall,log4j maxPoolPreparedStatementPerConnectionSize: 20 useGlobalDataSourceStat: true connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
3.在application.yml里配置Druid数据源其他参数后并不会生效,我们需要编写配置类,向容器里注入组件
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.servlet.Filter; import javax.servlet.ServletRegistration; import javax.sql.DataSource; import java.util.HashMap; @Configuration public class DruidConfig { @Bean @ConfigurationProperties(prefix = "spring.datasource") public DataSource druidDataSource(){ return new DruidDataSource(); } //后台监控 @Bean public ServletRegistrationBean statviewservlet(){ ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*"); //后台需要有人登陆,账号密码配置 HashMap<String, String> initParameters = new HashMap<>(); //登陆的key是固定的loginUsername loginPassword initParameters.put("loginUsername","admin"); //允许谁可以访问 initParameters.put("allow","localhost"); /**禁止谁能访问 *initParameters.put("xxxx","xxxx"); */ initParameters.put("loginPassword","123456"); bean.setInitParameters(initParameters);;//设置初始化参数 return bean; } //filter @Bean public FilterRegistrationBean webStartFilter(){ FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>(); bean.setFilter(new WebStatFilter()); //可以过滤哪些请求 HashMap<String, String> initParamters = new HashMap<>(); initParamters.put("exclusion","*.js,*.css,/druid/*"); bean.setInitParameters(initParamters);
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}
4.访问localhost:8080/druid可以查看监控信息