SpringBoot - Druid
2018-05-28 本文已影响52人
BzCoder
1.什么是Druid?
Druid是阿里的开源库,是Java语言中最好的数据库连接池。Druid能够提供强大的监控和扩展功能。
还有其实Druidf翻译过来就是大名鼎鼎的德鲁伊!看样子大神们都是很调皮的阿。
2. 配置Druid
其实大多数在GitHub上已经写的比较明白了。Maven参考文档。
参考https://github.com/alibaba/druid即可,但是还是有配置上的小坑,这里就列下配置文件。
applicaition.yml:
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://192.168.15.128:3306/jdbc
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
#dataSource Pool configuration
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
DruidConfig:
package com.example.jdbc.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
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 org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* @author BaoZhou
* @date 2018/5/25
*/
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid(){
return DruidDataSourceBuilder.create().build();
}
@Bean
public ServletRegistrationBean startViewServlet()
{
//参数可以在StatViewServlet和ResourceServlet中查看
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
Map<String,String> params = new HashMap<>();
//用户名
params.put("loginUsername","admin");
//密码
params.put("loginPassword","123456");
//IP白名单 (不填写代表允许所有IP)
params.put("allow","");
//IP黑名单 (存在共同时,deny优先于allow)
//initParameters.put("deny", "192.168.20.38");
bean.setInitParameters(params);
return bean;
}
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
Map<String,String> initParams = new HashMap<>();
//排除拦截
initParams.put("exclusions","*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}
运行后即可登录http://localhost:8080/druid/login.html查看监控讯息。
总的来说就是十分简单好用的数据库连接池,当然更多高级用法还是要参考GitHub文档。