中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

溫馨提示×

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

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

詳解SpringBoot配置連接池

發布時間:2020-10-20 04:01:14 來源:腳本之家 閱讀:230 作者:等風de帆 欄目:編程語言

內置的連接池

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

數據庫連接可以使用DataSource池進行自動配置。

  1. 由于Tomcat數據源連接池的性能和并發,在tomcat可用時,我們總是優先使用它。
  2. 如果HikariCP可用,我們將使用它。
  3. 如果Commons DBCP可用,我們將使用它,但在生產環境不推薦使用它。
  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能夠從大多數數據庫的url上推斷出driver-class-name,你就不需要再指定它了。對于一個將要創建的DataSource連接池,我們需要能夠驗證Driver是否可用,所以我們會在做任何事情之前檢查它。比如,如果你設置spring.datasource.driverClassName=com.MySQL.jdbc.Driver,然后這個類就會被加載。

配置Druid連接池

在SpringBoot 的1.5.2版本中不在支持自動配druid,,即無法通過配置項直接支持相應的連接池;這里列出的這些配置項可以通過定制化DataSource來實現。

druid介紹

Druid是一個JDBC組件,它包括三部分:

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

Druid可以做什么

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

項目地址: https://github.com/alibaba/druid

Spring Boot與Druid的集成

MySQL Driver驅動包:

    <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配置信息

# 驅動配置信息
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
## 配置獲取連接等待超時的時間
spring.druid.maxWait=60000
# 配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接,單位是毫秒
spring.druid.timeBetweenEvictionRunsMillis=60000
# 配置一個連接在池中最小生存的時間,單位是毫秒
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
# 配置監控統計攔截的filters,去掉后監控界面sql無法統計,'wall'用于防火墻
spring.druid.filters=stat,wall,log4j
# 通過connectProperties屬性來打開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實例
  @Primary //在同樣的DataSource中,首先使用被標注的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的實現類:

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黑名單 (存在共同時,deny優先于allow)
        @WebInitParam(name = "loginUsername", value = "admin"),// 用戶名
        @WebInitParam(name = "loginPassword", value = "123456"),// 密碼
        @WebInitParam(name = "resetEnable", value = "false")// 禁用HTML頁面上的“Reset All”功能
    })
public class DruidStatViewServlet extends StatViewServlet {
  private static final long serialVersionUID = -2688872071445249539L;
}

在啟動類上加入@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());    //添加初始化參數:initParams
    servletRegistrationBean.addUrlMappings("/druid/*");
    //白名單:
    servletRegistrationBean.addInitParameter("allow", "127.0.0.1");
    //IP黑名單 (存在共同時,deny優先于allow) : 如果滿足deny的話提示:Sorry, you are not permitted to view this page.
    servletRegistrationBean.addInitParameter("deny", "192.168.1.73");
    //登錄查看信息的賬號密碼.
    servletRegistrationBean.addInitParameter("loginUsername", "admin");
    servletRegistrationBean.addInitParameter("loginPassword", "123456");
    //是否能夠重置數據.
    servletRegistrationBean.addInitParameter("resetEnable", "false");
    return servletRegistrationBean;
  }

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

運行界面以及介紹

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

詳解SpringBoot配置連接池 

賬號和密碼為在servlet中配置的

詳解SpringBoot配置連接池

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

凤庆县| 宝兴县| 页游| 罗城| 鄱阳县| 武安市| 商水县| 屯留县| 井冈山市| 苗栗县| 阳原县| 宜城市| 静宁县| 容城县| 涿鹿县| 阿尔山市| 定远县| 铜鼓县| 孟津县| 建宁县| 项城市| 萍乡市| 依安县| 康平县| 阳高县| 金湖县| 云林县| 阳西县| 左权县| 开远市| 淮南市| 福泉市| 桦南县| 梅州市| 屯留县| 邓州市| 榆林市| 伊金霍洛旗| 景谷| 诸暨市| 内乡县|