赞
踩
SpringBoot整合Druid
1.导入依赖pom.xml
<!-- https://mvnrepository.com/artifact/log4j/log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!--JDBC--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.8</version> </dependency> <!--mysql驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency>
2.application.yml配置文件配置druid连接参数
大多都是固定参数,使用什么数据源就指定type即可
# 配置数据库 spring: datasource: url: jdbc:mysql://localhost:3306/ajax_db?useSSL=true&useUnicode=true&characterEncoding=utf8&serverTimeZone=Asia/Shanghai username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource # SpringBoot时默认是不注入这些属性值的,需要自己绑定 # druid 数据源专有配置 initialSize: 5 minIdle: 5 maxActive: 20 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 connectiomProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
3.自定义配置DruidConfig
@Configuration//放入容器中 public class DruidConfig { @Bean //绑定配置文件前缀为spring.datasource @ConfigurationProperties(prefix = "spring.datasource") public DataSource druidDataSource(){ return new DruidDataSource(); } /** * 返回后台监控servlet */ @Bean public ServletRegistrationBean monitor(){ //请求 ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*"); //后台需要用户登录,账号密码配置 HashMap<String, String> initParameters = new HashMap<>(); //增加配置 //登录key是固定的loginUsername loginPassword initParameters.put("loginUsername","admin"); initParameters.put("loginPassword","123456"); //访问白名单 initParameters.put("allow","ip地址"); bean.setInitParameters(initParameters);//设置初始化参数 return bean; } /** * filter * @return */ @Bean public FilterRegistrationBean webStatFilter(){ FilterRegistrationBean<Filter> filterBean = new FilterRegistrationBean<>(); filterBean.setFilter(new WebStatFilter()); //可以过滤那些请求 Map<String, String> initParameters = new HashMap<>(); //不统计这些东西 initParameters.put("exclusions","*.js,*.css,/druid/*"); filterBean.setInitParameters(initParameters); return filterBean; } }
4.配置完毕,启动项目,浏览器访问http://localhost:8080/druid/login.html,将后台设置的用户名和密码输入即可进入监控界面
具体测试图:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。