溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

詳解SpringBoot配置連接池

發(fā)布時(shí)間:2020-10-20 04:01:14 來(lái)源:腳本之家 閱讀:228 作者:等風(fēng)de帆 欄目:編程語(yǔ)言

內(nèi)置的連接池

目前spring Boot中默認(rèn)支持的連接池有dbcp,dbcp2, tomcat, hikari三種連接池。

數(shù)據(jù)庫(kù)連接可以使用DataSource池進(jìn)行自動(dòng)配置。

  1. 由于Tomcat數(shù)據(jù)源連接池的性能和并發(fā),在tomcat可用時(shí),我們總是優(yōu)先使用它。
  2. 如果HikariCP可用,我們將使用它。
  3. 如果Commons DBCP可用,我們將使用它,但在生產(chǎn)環(huán)境不推薦使用它。
  4. 最后,如果Commons DBCP2可用,我們將使用它。

以上的幾種連接池,可以通過在配置application文件中配置。

spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

Spring Boot能夠從大多數(shù)數(shù)據(jù)庫(kù)的url上推斷出driver-class-name,你就不需要再指定它了。對(duì)于一個(gè)將要?jiǎng)?chuàng)建的DataSource連接池,我們需要能夠驗(yàn)證Driver是否可用,所以我們會(huì)在做任何事情之前檢查它。比如,如果你設(shè)置spring.datasource.driverClassName=com.MySQL.jdbc.Driver,然后這個(gè)類就會(huì)被加載。

配置Druid連接池

在SpringBoot 的1.5.2版本中不在支持自動(dòng)配druid,,即無(wú)法通過配置項(xiàng)直接支持相應(yīng)的連接池;這里列出的這些配置項(xiàng)可以通過定制化DataSource來(lái)實(shí)現(xiàn)。

druid介紹

Druid是一個(gè)JDBC組件,它包括三部分:

  1. DruidDriver 代理Driver,能夠提供基于Filter-Chain模式的插件體系。
  2. DruidDataSource 高效可管理的數(shù)據(jù)庫(kù)連接池。
  3. SQLParser

Druid可以做什么

  1. 可以監(jiān)控?cái)?shù)據(jù)庫(kù)訪問性能,Druid內(nèi)置提供了一個(gè)功能強(qiáng)大的StatFilter插件,能夠詳細(xì)統(tǒng)計(jì)SQL的執(zhí)行性能,這對(duì)于線上分析數(shù)據(jù)庫(kù)訪問性能有幫助。
  2. 替換DBCP和C3P0。Druid提供了一個(gè)高效、功能強(qiáng)大、可擴(kuò)展性好的數(shù)據(jù)庫(kù)連接池。
  3. 數(shù)據(jù)庫(kù)密碼加密。直接把數(shù)據(jù)庫(kù)密碼寫在配置文件中,這是不好的行為,容易導(dǎo)致安全問題。DruidDruiver和DruidDataSource都支持PasswordCallback。
  4. SQL執(zhí)行日志,Druid提供了不同的LogFilter,能夠支持Common-Logging、Log4j和JdkLog,你可以按需要選擇相應(yīng)的LogFilter,監(jiān)控你應(yīng)用的數(shù)據(jù)庫(kù)訪問情況。
  5. 擴(kuò)展JDBC,如果你要對(duì)JDBC層有編程的需求,可以通過Druid提供的Filter-Chain機(jī)制,很方便編寫JDBC層的擴(kuò)展插件。 

項(xiàng)目地址: https://github.com/alibaba/druid

Spring Boot與Druid的集成

MySQL Driver驅(qū)動(dòng)包:

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <scope>runtime</scope>
    </dependency>

阿里系的Druid依賴包:

    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.0.25</version>
    </dependency>

application.properties配置信息

# 驅(qū)動(dòng)配置信息
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url = jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8 
spring.datasource.username = root
spring.datasource.password = adminter
spring.datasource.driverClassName = com.mysql.jdbc.Driver

#連接池的配置信息
## 初始化大小,最小,最大
spring.druid.initialSize=5
spring.druid.minIdle=5
spring.druid.maxActive=20
## 配置獲取連接等待超時(shí)的時(shí)間
spring.druid.maxWait=60000
# 配置間隔多久才進(jìn)行一次檢測(cè),檢測(cè)需要關(guān)閉的空閑連接,單位是毫秒
spring.druid.timeBetweenEvictionRunsMillis=60000
# 配置一個(gè)連接在池中最小生存的時(shí)間,單位是毫秒
spring.druid.minEvictableIdleTimeMillis=300000
spring.druid.validationQuery=SELECT 1 FROM DUAL
spring.druid.testWhileIdle=true
spring.druid.testOnBorrow=false
spring.druid.testOnReturn=false
spring.druid.poolPreparedStatements=true
spring.druid.maxPoolPreparedStatementPerConnectionSize=20
# 配置監(jiān)控統(tǒng)計(jì)攔截的filters,去掉后監(jiān)控界面sql無(wú)法統(tǒng)計(jì),'wall'用于防火墻
spring.druid.filters=stat,wall,log4j
# 通過connectProperties屬性來(lái)打開mergeSql功能;慢SQL記錄
spring.druid.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000

DruidSource配置信息的定制

package com.lf.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * Created by LF on 2017/4/18.
 */
@ConfigurationProperties(prefix = "spring.druid")
public class DruidSource {

  private String dbUrl;

  private String username;

  private String password;

  private String driverClassName;

  private int initialSize;

  private int minIdle;

  private int maxActive;

  private int maxWait;

  private int timeBetweenEvictionRunsMillis;

  private int minEvictableIdleTimeMillis;
  private String validationQuery;

  private boolean testWhileIdle;
  private boolean testOnBorrow;

  private boolean testOnReturn;

  private boolean poolPreparedStatements;

  private int maxPoolPreparedStatementPerConnectionSize;

  private String filters;

  private String connectionProperties;

  public String getDbUrl() {
    return dbUrl;
  }

  public void setDbUrl(String dbUrl) {
    this.dbUrl = dbUrl;
  }

  public String getUsername() {
    return username;
  }

  public void setUsername(String username) {
    this.username = username;
  }

  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    this.password = password;
  }

  public String getDriverClassName() {
    return driverClassName;
  }

  public void setDriverClassName(String driverClassName) {
    this.driverClassName = driverClassName;
  }

  public int getInitialSize() {
    return initialSize;
  }

  public void setInitialSize(int initialSize) {
    this.initialSize = initialSize;
  }

  public int getMinIdle() {
    return minIdle;
  }

  public void setMinIdle(int minIdle) {
    this.minIdle = minIdle;
  }

  public int getMaxActive() {
    return maxActive;
  }

  public void setMaxActive(int maxActive) {
    this.maxActive = maxActive;
  }

  public int getMaxWait() {
    return maxWait;
  }

  public void setMaxWait(int maxWait) {
    this.maxWait = maxWait;
  }

  public int getTimeBetweenEvictionRunsMillis() {
    return timeBetweenEvictionRunsMillis;
  }

  public void setTimeBetweenEvictionRunsMillis(int timeBetweenEvictionRunsMillis) {
    this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
  }

  public int getMinEvictableIdleTimeMillis() {
    return minEvictableIdleTimeMillis;
  }

  public void setMinEvictableIdleTimeMillis(int minEvictableIdleTimeMillis) {
    this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
  }

  public String getValidationQuery() {
    return validationQuery;
  }

  public void setValidationQuery(String validationQuery) {
    this.validationQuery = validationQuery;
  }

  public boolean isTestWhileIdle() {
    return testWhileIdle;
  }

  public void setTestWhileIdle(boolean testWhileIdle) {
    this.testWhileIdle = testWhileIdle;
  }

  public boolean isTestOnBorrow() {
    return testOnBorrow;
  }

  public void setTestOnBorrow(boolean testOnBorrow) {
    this.testOnBorrow = testOnBorrow;
  }

  public boolean isTestOnReturn() {
    return testOnReturn;
  }

  public void setTestOnReturn(boolean testOnReturn) {
    this.testOnReturn = testOnReturn;
  }

  public boolean isPoolPreparedStatements() {
    return poolPreparedStatements;
  }

  public void setPoolPreparedStatements(boolean poolPreparedStatements) {
    this.poolPreparedStatements = poolPreparedStatements;
  }

  public int getMaxPoolPreparedStatementPerConnectionSize() {
    return maxPoolPreparedStatementPerConnectionSize;
  }

  public void setMaxPoolPreparedStatementPerConnectionSize(int maxPoolPreparedStatementPerConnectionSize) {
    this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize;
  }

  public String getFilters() {
    return filters;
  }

  public void setFilters(String filters) {
    this.filters = filters;
  }

  public String getConnectionProperties() {
    return connectionProperties;
  }

  public void setConnectionProperties(String connectionProperties) {
    this.connectionProperties = connectionProperties;
  }

  @Bean   //聲明其為Bean實(shí)例
  @Primary //在同樣的DataSource中,首先使用被標(biāo)注的DataSource
  public DataSource dataSource() throws SQLException {
    DruidDataSource datasource = new DruidDataSource();

    datasource.setUrl(this.dbUrl);
    datasource.setUsername(username);
    datasource.setPassword(password);
    datasource.setDriverClassName(driverClassName);

    //configuration
    datasource.setInitialSize(initialSize);
    datasource.setMinIdle(minIdle);
    datasource.setMaxActive(maxActive);
    datasource.setMaxWait(maxWait);
    datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    datasource.setValidationQuery(validationQuery);
    datasource.setTestWhileIdle(testWhileIdle);
    datasource.setTestOnBorrow(testOnBorrow);
    datasource.setTestOnReturn(testOnReturn);
    datasource.setPoolPreparedStatements(poolPreparedStatements);
    datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);

    datasource.setFilters(filters);


    return datasource;
  }
}

基于注解的配置StatView的Servlet

Filter的實(shí)現(xiàn)類:

package com.lf.config;

import com.alibaba.druid.support.http.WebStatFilter;

import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;

/**
 * Created by LF on 2017/4/18.
 */
@WebFilter(filterName = "druidWebStatFilter", urlPatterns = "/*",
    initParams = {
        @WebInitParam(name = "exclusions", value = "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")//忽略資源
    }
)
public class DruidStatFilter extends WebStatFilter {
}

StatViewServlet:

package com.lf.config;

import com.alibaba.druid.support.http.StatViewServlet;

import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;

/**
 * Created by LF on 2017/4/18.
 */

@WebServlet(urlPatterns = "/druid/*",
    initParams = {
        @WebInitParam(name = "allow", value = "127.0.0.1,192.168.163.1"),// IP白名單(沒有配置或者為空,則允許所有訪問)
        @WebInitParam(name = "deny", value = "192.168.1.73"),// IP黑名單 (存在共同時(shí),deny優(yōu)先于allow)
        @WebInitParam(name = "loginUsername", value = "admin"),// 用戶名
        @WebInitParam(name = "loginPassword", value = "123456"),// 密碼
        @WebInitParam(name = "resetEnable", value = "false")// 禁用HTML頁(yè)面上的“Reset All”功能
    })
public class DruidStatViewServlet extends StatViewServlet {
  private static final long serialVersionUID = -2688872071445249539L;
}

在啟動(dòng)類上加入@ServletComponentScan注解

基于Java的配置StatView的Servlet

package com.lf.config;

import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
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;

/**
 * Created by LF on 2017/4/18.
 */
@Configuration
public class DruidConfig {
  @Bean
  public ServletRegistrationBean registrationBean() {
    ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet());    //添加初始化參數(shù):initParams
    servletRegistrationBean.addUrlMappings("/druid/*");
    //白名單:
    servletRegistrationBean.addInitParameter("allow", "127.0.0.1");
    //IP黑名單 (存在共同時(shí),deny優(yōu)先于allow) : 如果滿足deny的話提示:Sorry, you are not permitted to view this page.
    servletRegistrationBean.addInitParameter("deny", "192.168.1.73");
    //登錄查看信息的賬號(hào)密碼.
    servletRegistrationBean.addInitParameter("loginUsername", "admin");
    servletRegistrationBean.addInitParameter("loginPassword", "123456");
    //是否能夠重置數(shù)據(jù).
    servletRegistrationBean.addInitParameter("resetEnable", "false");
    return servletRegistrationBean;
  }

  @Bean
  public FilterRegistrationBean filterRegistrationBean() {
    FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
    //添加過濾規(guī)則.
    filterRegistrationBean.addUrlPatterns("/*");
    //添加不需要忽略的格式信息.
    filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
    return filterRegistrationBean;
  }
}

運(yùn)行界面以及介紹

訪問地址: http://192.168.163.1:8080/druid/index.html

詳解SpringBoot配置連接池 

賬號(hào)和密碼為在servlet中配置的

詳解SpringBoot配置連接池

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI