Druid 数据源
Druid能够提供强大的监控和扩展功能。隶属于阿里巴巴旗下的连接池
我们使用druid和SpingBoot结合
首先我们引入druid 的maven依赖
1 | <!-- https://mvnrepository.com/artifact/com.alibaba/druid --> |
yml配置如下1
2
3
4
5
6
7spring:
datasource:
username: root
password: root
url: jdbc:mysql://192.168.13.131:3306/springboot01
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
我们仍然可以使用druid其他的yml配置1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17# 数据源其他配置
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
然后由于很多属性值druid无法映射,我们可以使用yml属性绑定的方式1
2
3
4
5"spring.datasource") (prefix =
public DataSource druid(){
return new DruidDataSource();
}
然后我们需要配置druid的后台管理servlet以及监控的filter1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23//配置管理后台的servlet
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
Map<String,String> map = new HashMap<>();
map.put("loginUsername","admin");
map.put("loginPassword","admin");
map.put("allow","");//默认允许所有访问
map.put("deny","192.168.13.132");//禁止192.168.13.132访问
bean.setInitParameters(map);//初始化参数
return bean;
}
//配置一个web监控的filter
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
bean.setFilter(new WebStatFilter());
Map<String,String> map = new HashMap<>();
map.put("exclusions","*.js,*.css,/druid/*"); //不拦截这些
bean.setInitParameters(map); //初始化参数
bean.setUrlPatterns(Arrays.asList("/*")); //表示拦截所有请求
return bean;
}
然后输入localhost/druid就可运行成功