SpringBoot整合Druid
本文内容纲要:
最近一直在折腾springboot,也根据需要整合了一些好用的库,mybatis作为持续层数据操作,也想用一下大名鼎鼎的Druid来做连接池和数据库监控服务。于是摸索了一下午,整理出这篇小文,希望能帮助到同道,也给自己做个记录反思。
- 1.关于Druid
Druid是阿里团队开源的高性能数据库连接池,国内使用广泛,特别是在监控sql和数据库性能方面非常强大。
连接池能有效节省数据库连接消耗,且对高写入、实时性要求高的业务非常合适。
-
2.引入依赖到pom.xml中。
com.alibaba druid-spring-boot-starter1.1.10 -
3.然后在application.yml中设置相关配置
spring: datasource: url:jdbc:mysql://127.0.0.1:3306/test_go?characterEncoding=UTF-8&useSSL=false username:xxx password:xxxxxx driver-class-name:com.mysql.jdbc.Driver type:com.alibaba.druid.pool.DruidDataSource druid: initial-size:5 min-idle:5 max-active:20 test-while-idle:true test-on-borrow:false test-on-return:false pool-prepared-statements:true max-pool-prepared-statement-per-connection-size:20 max-wait:60000 time-between-eviction-runs-millis:60000 min-evictable-idle-time-millis:30000 filters:stat async-init:true
其中最重要的是
type:com.alibaba.druid.pool.DruidDataSource
这样就不会使用Springboot默认的连接池Hikari。
由于SpringBoot没法生效写在yml文件中的配置,需要单独编写Bean文件来加载。
-
4.定义Druid配置类。
packagecom.tony.testspringboot.config;
importcom.alibaba.druid.pool.DruidDataSource; importorg.slf4j.Logger; importorg.slf4j.LoggerFactory; importorg.springframework.beans.factory.annotation.Value; importorg.springframework.context.annotation.Bean; importorg.springframework.context.annotation.Configuration; importorg.springframework.context.annotation.Primary;
importjavax.sql.DataSource; importjava.sql.SQLException;
@Configuration publicclassDruidConfig{ privateLoggerlogger=LoggerFactory.getLogger(DruidConfig.class);
@Value("${spring.datasource.url}") privateStringdbUrl; @Value("${spring.datasource.username}") privateStringusername; @Value("${spring.datasource.password}") privateStringpassword; @Value("${spring.datasource.test-druid.driver-class-name}") privateStringdriverClassName; @Value("${spring.datasource.druid.initial-size}") privateintinitialSize; @Value("${spring.datasource.druid.min-idle}") privateintminIdle; @Value("${spring.datasource.druid.max-active}") privateintmaxActive; @Value("${spring.datasource.druid.max-wait}") privateintmaxWait; @Value("${spring.datasource.druid.time-between-eviction-runs-millis}") privateinttimeBetweenEvictionRunsMillis; @Value("${spring.datasource.druid.min-evictable-idle-time-millis}") privateintminEvictableIdleTimeMillis; @Value("${spring.datasource.druid.test-while-idle}") privatebooleantestWhileIdle; @Value("${spring.datasource.druid.test-on-borrow}") privatebooleantestOnBorrow; @Value("${spring.datasource.druid.test-on-return}") privatebooleantestOnReturn; @Value("${spring.datasource.druid.pool-prepared-statements}") privatebooleanpoolPreparedStatements; @Value("${spring.datasource.druid.max-pool-prepared-statement-per-connection-size}") privateintmaxPoolPreparedStatementPerConnectionSize; @Value("${spring.datasource.druid.filters}") privateStringfilters; @Bean @Primary publicDataSourcedataSource(){ DruidDataSourcedatasource=newDruidDataSource(); datasource.setUrl(this.dbUrl); datasource.setUsername(this.username); datasource.setPassword(this.password); datasource.setDriverClassName(this.driverClassName); //configuration datasource.setInitialSize(this.initialSize); datasource.setMinIdle(this.minIdle); datasource.setMaxActive(this.maxActive); datasource.setMaxWait(this.maxWait); datasource.setTimeBetweenEvictionRunsMillis(this.timeBetweenEvictionRunsMillis); datasource.setMinEvictableIdleTimeMillis(this.minEvictableIdleTimeMillis); datasource.setTestWhileIdle(this.testWhileIdle); datasource.setTestOnBorrow(this.testOnBorrow); datasource.setTestOnReturn(this.testOnReturn); datasource.setPoolPreparedStatements(this.poolPreparedStatements); datasource.setMaxPoolPreparedStatementPerConnectionSize(this.maxPoolPreparedStatementPerConnectionSize); try{ datasource.setFilters(this.filters); }catch(SQLExceptione){ logger.error("druidconfigurationinitfail!"); } returndatasource; }
}
如此即可让配置的参数生效并作为首选的DataSource进行使用。
5.在Controller中测试。
可以使用JdbcTemplate来进行查询。
测试代码如下所示:
@RequestMapping(value="/hey",method=RequestMethod.GET)
publicResultResponsetestDruid(){
Stringsql="SELECTmobileFROMuserWHEREid=?";
Stringmobile=jdbcTemplate.queryForObject(sql,newObject[]{1},String.class);
returnnewResultResponse(201,"hey"+mobile);
}
PS:ResultResponse是我项目中封装的通用response对象。
关于多数据源参数的设置。
只需要在yml(application.yml)中设置即可,格式如下:
datasource:
one-source:
url:jdbc:mysql://127.0.0.1:3306/test_go?characterEncoding=UTF-8&useSSL=false
username:xxxx1
password:xxxx
driver-class-name:com.mysql.jdbc.Driver
type:com.alibaba.druid.pool.DruidDataSource
two-source:
url:jdbc:mysql://127.0.0.1:3306/demo2?characterEncoding=UTF-8&useSSL=false
username:xxxx
password:1xxxxxx
driver-class-name:com.mysql.jdbc.Driver
type:com.alibaba.druid.pool.DruidDataSource
...
使用的时候也遵循这个结构,如要获取第一个数据源的url配置则在DruidConfig.java文件中的相应项的@Value中这样写:
@Value("${spring.datasource.one-source.url}")
privateStringdbUrl;
- 6.配置数据库监控。
a)先在application.yml中增加如下配置:
druid:
.....
#通过connectProperties属性来打开mergeSql功能;慢SQL记录
connection-properties:druid.stat.mergeSql=true;druid.stat.SlowSqlMills=5000
#监控后台的配置,如登录账号和密码等
monitor:
allow:127.0.0.1
loginUsername:admin
loginPassword:admin
b)单独编写DruidMonitorConfiguration类。
publicclassDruidMonitorConfiguration{
@Value("${spring.datasource.druid.monitor.allow}")
privateStringallow;
//@Value("${spring.datasource.druid.monitor.deny}")
//privateStringdeny;
@Value("${spring.datasource.druid.monitor.loginUsername}")
privateStringloginUsername;
@Value("${spring.datasource.druid.monitor.loginPassword}")
privateStringloginPassword;
@Value("${spring.datasource.druid.monitor.resetEnable")
privateStringresetEnable;
@Bean
publicServletRegistrationBeandruidStatViewServlet(){
ServletRegistrationBeanservletRegistrationBean=newServletRegistrationBean(newStatViewServlet(),"/druid/*");
servletRegistrationBean.addInitParameter("allow",this.allow);
//servletRegistrationBean.addInitParameter("deny",this.deny);
servletRegistrationBean.addInitParameter("loginUsername",this.loginUsername);
servletRegistrationBean.addInitParameter("loginPassword",this.loginPassword);
servletRegistrationBean.addInitParameter("resetEnable",this.resetEnable);
returnservletRegistrationBean;
}
@Bean
publicFilterRegistrationBeandruidStatFilter(){
FilterRegistrationBeanfilterRegistrationBean=newFilterRegistrationBean(newWebStatFilter());
filterRegistrationBean.addUrlPatterns("/*");
filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
returnfilterRegistrationBean;
}
}
访问方法就是:
验证登录即可。整个监控功能十分强大,有sql监控、URI监控、Session监控,Web应用等等。
本文内容总结:
原文链接:https://www.cnblogs.com/freephp/p/11688387.html