springboot整合Druid数据源
什么是Druid?
Druid是一个高效的数据查询系统,主要解决的是对于大量的基于时序的数据进行聚合查询。
Druid的依赖:
<!--如果遇到版本问题,请自行更换版本-->
<!--Druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.21</version>
</dependency>
<!--log4j-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
application.yaml配置
spring:
datasource:
username: root
password: xxxxx
url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
#springBoot默认是不注入这些属性值的,需要自己绑定
#druid数据源专有配置
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依赖即可,Maven地址:https://mvnrepository.com/artifact/log4j/log4j
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
在启动类的同级目录下,建立文件夹config,在新建DruidConfig类:
DruidConfig.java
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druiDataSource(){
return new DruidDataSource();
}
//后台监控
//因为springboot内置了servlet容器,所有没有web.xml,替代方法:ServletRegistrationBean
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
//后台需要有人登录,账号密码配置
HashMap<String,String> initParameters = new HashMap<>();
//增加配置 loginUsername,loginPassword时固定的不能修改,账户和密码可以随意设置
initParameters.put("loginUsername","admin");
initParameters.put("loginPassword","123456");
//允许谁可以访问
initParameters.put("allow","");
//禁止谁不能访问 initParameters.put("ws","192.168.11.123");
//设置初始化参数
bean.setInitParameters(initParameters);
return bean;
}
//filter 过滤器
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
//可以过滤哪些请求呢?
Map<String, String> initParameters = new HashMap<>();
//这些东西不进行统计
initParameters.put("exclusions","*.js,*.css,/druid/*");
bean.setInitParameters(initParameters);
return bean;
}
}
项目配置好后,运行项目(请求路径为:http://localhost:8080/druid,上面设置的账户为:admin,密码为:123456),如图
登录后
表示配置成功了!