springboot集成druid
Spring Boot 2.0 以上默认使用 com.zaxxer.hikari.HikariDataSource 数据源,但可以通过spring.datasource.type 指定数据源。
1、引依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.13</version>
</dependency>
<!--log4j-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
2、配置数据源
#配置mysql数据源
spring:
datasource:
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/hotel_system?useCode=true
type: com.alibaba.druid.pool.DruidDataSource
#druid连接池的配置,springboot默认不配置
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
connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMills=500
filters: stat,log4j,wall
connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMills=500
注意:上述两个参数必须填写,否则数据源页面filter为空,监控不了sql。
3、测试是否切换成功
@Autowired
private DataSource dataSource;
@Test
void contextLoads() throws Exception {
System.out.println(dataSource.getClass());
}
4、配置后台监控
编写配置类
温馨提示:配置类的初始化参数中的key不能乱写,固定的
@Configuration
public class DruidConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource druidDataSource(){
return new DruidDataSource();
}
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<StatViewServlet>(new StatViewServlet(), "/druid/*");
HashMap<String, String> initParameters = new HashMap<>();
//后台管理界面的登录账号
initParameters.put("loginUsername", "admin");
//后台管理界面的登录密码
initParameters.put("loginPassword", "123456");
//允许谁访问,""表示所有人可以访问druid登录页面
initParameters.put("allow", "");
bean.setInitParameters(initParameters);
return bean;
}
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
bean.setFilter(new WebStatFilter());
HashMap<String, String> initParameter = new HashMap<>();
initParameter.put("exclusions", "*.js,*.css,*.font,*.fonts,*.images,*.map,*.sass,/druid/*");
bean.setInitParameters(initParameter);
return bean;
}
}
5、访问/druid后台监控
账户密码在上述配置类,输入登录即可