Druid 连接池

979 阅读1分钟

前言:本文简单介绍了Druid数据库连接池的使用,主要是与Spring Boot框架整合使用。通过使用连接池可以大大提高与数据库交互的效率。

Druid 官网

Druid 官方文档

Druid 中文文档

简介

Apache Druid是一个实时分析型数据库,旨在对大型数据集进行快速的查询分析("OLAP"查询)。Druid最常被当做数据库来用以支持实时摄取、高性能查询和高稳定运行的应用场景,同时,Druid也通常被用来助力分析型应用的图形化界面,或者当做需要快速聚合的高并发后端API,Druid最适合应用于面向事件类型的数据。

导入数据源

Maven Druid

 <dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>druid</artifactId>
     <version>${druid.version}</version>
 </dependency>

数据库连接池配置

spring

com.alibaba.druid.pool.DruidDataSource

 <!--数据库连接池配置 -->
 <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
     <property name="driverClassName" value="${jdbc.driverClassName}" />
     <property name="url" value="${jdbc.url}" />
     <property name="username" value="${jdbc.username}" />
     <property name="password" value="${jdbc.password}" />
     <!-- 配置初始化大小、最小、最大 -->
     <property name="initialSize" value="1" />
     <property name="minIdle" value="1" />
     <property name="maxActive" value="50" />
     <!-- 配置获取连接等待超时的时间 -->
     <property name="maxWait" value="30000" />
 ​
     <property name="filters" value="stat,wall" />
     <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
     <property name="timeBetweenEvictionRunsMillis" value="3000" />
     <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
     <property name="minEvictableIdleTimeMillis" value="300000" />
     
     <property name="validationQuery" value="SELECT 'x'" />
     <property name="testWhileIdle" value="true" />
     <!-- 这里建议配置为TRUE,防止取到的连接不可用 -->
     <property name="testOnBorrow" value="false" />
     <property name="testOnReturn" value="false" />
     <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
     <property name="poolPreparedStatements" value="true" />
     <property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
 </bean>

springboot

 spring:
   datasource:
     driver-class-name: com.mysql.cj.jdbc.Driver
     url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
     username: ${jdbc.username}
     password: ${jdbc.password}
     type: com.alibaba.druid.pool.DruidDataSource
     
     #druid 数据源专有配置
     # 初始化大小,最小,最大
     initialSize: 5
     minIdle: 5
     maxActive: 20
     # 配置获取连接等待超时的时间
     maxWait: 60000
     # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
     timeBetweenEvictionRunsMillis: 60000
     # 配置一个连接在池中最小生存的时间,单位是毫秒
     minEvictableIdleTimeMillis: 300000
     validationQuery: SELECT 1 FROM DUAL
     testWhileIdle: true
     testOnBorrow: false
     testOnReturn: false
     # 打开PSCache,并且指定每个连接上PSCache的大小
     poolPreparedStatements: true
     
     #配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入(防火墙)
     filters: stat,wall,log4j
     maxPoolPreparedStatementPerConnectionSize: 20
     # 合并多个DruidDataSource的监控数据
     useGlobalDataSourceStat: true
     # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
     connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

导入Log4j依赖

不导入可能会报java.lang.ClassNotFoundException: org.apache.log4j.Priority错误

 <dependency>
     <groupId>log4j</groupId>
     <artifactId>log4j</artifactId>
     <version>1.2.17</version>
 </dependency>

绑定DruidDataSource

需要自行添加到容器中并绑定属性

 @Configuration
 public class DruidConfig {
     @Bean
     @ConfigurationProperties(prefix = "spring.datasource")
     public DataSource druidDataSource() {
         return new DruidDataSource();
     }
 }

配置后台监控页面

Druid具有监控功能,有一个后台监控页面,配置后即可使用

监控页面页面:http://localhost:8080/druid/

     // 后台监控
     @Bean
     public ServletRegistrationBean statViewServlet() {
         ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");   // 设置后台路径
         HashMap<String, String> initParams = new HashMap<>();
         initParams.put("loginUsername", "admin");   // 登录账号
         initParams.put("loginPassword", "123456");  // 登录密码
         initParams.put("allow", "");    // 允许所有访问
         bean.setInitParameters(initParams);     // 设置初始化参数
         return bean;
     }

配置web监控过滤器

     // web监控过滤器
     @Bean
     public FilterRegistrationBean webStatFilter() {
         FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
         bean.setFilter(new WebStatFilter());
         Map<String, String> initParams = new HashMap<>();
         initParams.put("exclusions", "*.js, *.css, /druid/*");  // 过滤排除
         bean.setInitParameters(initParams);
         return bean;
     }

参考资料

【狂神说Java】SpringBoot最新教程IDEA版通俗易懂