您现在的位置是: 首页> java框架 > 正文

十.SpringBoot配置Druid连接池

时间: 2022-05-17 23:12:48 来源:网络 作者:自由 分类:java框架
简介:

连接池的作用是为了提高性能,将已经创建好的连接保存在池中,当有请求来时,直接使用已经创建好的连接对Server端进行访问。这样省略(复用)了创建连接和销毁连接的过程(TCP连接建立时的三次握手和销毁时的四次握手),从而在性能上得到了提高。

简介:

     连接池的作用是为了提高性能,将已经创建好的连接保存在池中,当有请求来时,直接使用已经创建好的连接对Server端进行访问。这样省略(复用)了创建连接和销毁连接的过程(TCP连接建立时的三次握手和销毁时的四次握手),从而在性能上得到了提高。Druid是一个JDBC组件,它包括三部分:DruidDriver 代理Driver,能够提供基于Filter-Chain模式的插件体系、DruidDataSource 高效可管理的数据库连接池、SQLParser。可以监控数据库访问性能,Druid内置提供了一个功能强大的StatFilter插件,能够详细统计SQL的执行性能,这对于线上分析数据库访问性能有帮助。

一.SpringBoot配置Druid连接池

1.在pom.xml中引用

<!-- 数据库 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<!--引入阿里巴巴druid连接池-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.6</version>
</dependency>
<!--自启动Druid管理后台-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.10</version>
</dependency>

2.配置application.yml

server:
  port: 8083
  session:
    timeout: 1800
spring:
  aop:
    auto: true
    proxy-target-class: false
  thymeleaf:
    #验证模板是否存在
    check-template: false
    check-template-location: false
    mode: HTML
    prefix: classpath:/templates/
  profiles:
    active: dev
    #连接池的配置信息
  druid:
    ## 初始化大小,最小,最大
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxPoolPreparedStatementPerConnectionSize: 20
    ## 配置获取连接等待超时的时间
    maxWait: 60000
    # 配置一个连接在池中最小生存的时间,单位是毫秒
    minEvictableIdleTimeMillis: 300000
    poolPreparedStatements: true
    #申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。
    testOnBorrow: false
    #归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。
    testOnReturn: false
    #建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
    testWhileIdle: true
    #连接保持空闲而不被驱逐的最小时间
    timeBetweenEvictionRunsMillis: 60000
    #用来检测连接是否有效的sql,要求是一个查询语句
    validationQuery: SELECT 1 FROM DUAL
    # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
    filters: stat,wall,log4j
    # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
    useGlobalDataSourceStat: true
    loginUsername: admin  # SQL监控后台登录用户名
    loginPassword: 1  # SQL监控后台登录用户密码

3.新建一个Druid的配置文件DruidConfig

package com.tms.tblog.infrastructure.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;

import com.alibaba.druid.pool.DruidDataSource;
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.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * Druid连接池配置
 */
@Configuration
public class DruidConfig {

    @Value("${spring.druid.loginUsername}")
    private String loginUsername;

    @Value("${spring.druid.loginPassword}")
    private String loginPassword;

    //加载application.yaml中的Druid配置
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druid() {
        return new DruidDataSource();
    }

    //配置Druid的监控
    //1、配置一个管理后台的Servlet
    @Bean
    public ServletRegistrationBean statViewServlet() {
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        Map<String, String> initParams = new HashMap<>();

        initParams.put("loginUsername", loginUsername);// druid的密码
        initParams.put("loginPassword", loginPassword); // druid的用户名
        initParams.put("allow", ""); // 默认就是允许所有访问 IP白名单 (没有配置或者为空,则允许所有访问)
        initParams.put("deny", "");  // IP黑名单 (存在共同时,deny优先于allow)

        bean.setInitParameters(initParams);
        return bean;
    }

    /**
     * 配置一个web监控的filter
     * @return
     */
    @Bean
    public FilterRegistrationBean webStatFilter() {

        FilterRegistrationBean bean = new FilterRegistrationBean(new WebStatFilter());
        // 添加过滤规则
        Map<String, String> initParams = new HashMap<>(1);
        // 设置忽略请求
        initParams.put("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*");
        bean.setInitParameters(initParams);
        bean.addInitParameter("profileEnable", "true");
        bean.addInitParameter("principalCookieName", "USER_COOKIE");
        bean.addInitParameter("principalSessionName", "");
        bean.addInitParameter("aopPatterns", "com.example.demo.service");
        // 验证所有请求
        bean.addUrlPatterns("/*");
        return bean;
    }
}

二.运行结果

1.启动程序然后在浏览器上输入http://localhost:8083/druid进入登录界面,输入druid的用户名密码就能登录进去了

 

标签:SpringBoot框架

文章声明
版权声明:本文为作者原创,仅用于本站访客学习、研究和交流目的,未经授权禁止转载
联系 作者

一个90后草根站长!13年入行。一直潜心研究技术,一边工作一边积累经验,分享一些个人后端技术(java、python、c#、php等),以及前端相关等心得。