首頁 > Java > java教程 > 主體

springboot druid資料庫連線池連線失敗後一直重連怎麼解決

王林
發布: 2023-05-21 11:28:25
轉載
3189 人瀏覽過

當我使用個人阿里雲測試機時,在查看即時輸出日誌時,我發現資料庫連線失敗後,伺服器一直在嘗試重新連線。一開始認為系統遭受了連續的攻擊,但是在重新啟動服務後,就不再出現不斷重連的情況了。看以下輸出日誌:

2022-02-09 11:04:58.896 ERROR 16876 --- [eate-1550991149] com.alibaba.druid.pool.DruidDataSource   : create connection SQL. jdbc:mysql://47.98.67,98:1234/test?useSSL=false&characterEncoding=UTF-8&serverTimezone=UTC, errorCode 1045, state 28000

.sql.SQLExrootception: Access debt' @'113.90.123.76' (using password: YES)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129) ~[my-connector-javajar-8.0.1SQLError.java:129) ~[my-connector-javajar-8.116. 8.0.16]
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.16.jar:8.0.16] ~[mysql-connector-java-8.0.16.jar:8.0.16] ##o com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.16.jar:8.0.16]
    at com.mysql  at com.mysql c.b. ConnectionImpl。 :455) ~[mysql-connector-java-8.0.16.jar:8.0.16]
    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:240) ~[mysql-connector-java -8.0.16.jar:8.0.16]
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:199) ~[mysql-connector-java-8.0.16.jarr.java:199) ~[mysql-connector-java-8.0.16.jar:8.0.16 ]
    at com.alibaba.druid.filter.FilterChainImpl.connection_connect(FilterChainImpl.java:156) ~[druid-1.1.10.jar:1.1.10]
    at com.b. .StatFilter.connection_connect(StatFilter.java:218) ~[druid-1.1.10.jar:1.1.10]
    at com.alibaba.druid.filter.FilterChainImpl.connection_connect(alibaba.druid.filter.FilterChainImpl.connection_connect(alibaba.druid.filter.FilterChainImpl.connection_connect( -1.1.10.jar:1.1.10]
    at com.alibaba.druid.pool.DruidAbstractDataSource.createPhysicalConnection(DruidAbstractDataSource.java:1560) ~[druid-1.1.10.jar:1.1.10]
at com.alibaba.druid.pool.DruidAbstractDataSource.createPhysicalConnection(DruidAbstractDataSource.java:1623) ~[druid-1.1.10.jar:1.1.10]
    at com.alibabaConnection.jardruid.DruConnection. (DruidDataSource.java:2468) ~[druid-1.1.10.jar:1.1.10]

注意上面一直有druid 資料庫連結池的提示,這裡就想到可能是druid 連結池的問題,然後去掉druid maven 依賴後在請求介面就不會出現重連的問題。

druid 重連原因

在上圖原始碼找到最後一行DruidDataSource.java:2468 定位到原始碼上,CreateConnectionThread 建立連線Connection,看看CreateThread 原始碼:

public class CreateConnectionThread extends Thread {

        public CreateConnectionThread(String name){
            super(name);
            this.setDaemon(true);
        }

        public void run() {
            initedLatch.countDown();

            long lastDiscardCount = 0;
            int errorCount = 0;
            for (;;) {
                // addLast
                try {
                    lock.lockInterruptibly();
                } catch (InterruptedException e2) {
                    break;
                }

                long discardCount = DruidDataSource.this.discardCount;
                boolean discardChanged = discardCount - lastDiscardCount > 0;
                lastDiscardCount = discardCount;

                try {
                    boolean emptyWait = true;

                    if (createError != null
                            && poolingCount == 0
                            && !discardChanged) {
                        emptyWait = false;
                    }

                    if (emptyWait
                            && asyncInit && createCount < initialSize) {
                        emptyWait = false;
                    }

                    if (emptyWait) {
                        // 必须存在线程等待,才创建连接
                        if (poolingCount >= notEmptyWaitThreadCount //
                                && !(keepAlive && activeCount + poolingCount < minIdle)) {
                            empty.await();
                        }

                        // 防止创建超过maxActive数量的连接
                        if (activeCount + poolingCount >= maxActive) {
                            empty.await();
                            continue;
                        }
                    }

                } catch (InterruptedException e) {
                    lastCreateError = e;
                    lastErrorTimeMillis = System.currentTimeMillis();

                    if (!closing) {
                        LOG.error("create connection Thread Interrupted, url: " + jdbcUrl, e);
                    }
                    break;
                } finally {
                    lock.unlock();
                }

                PhysicalConnectionInfo connection = null;

                try {
                    connection = createPhysicalConnection();
                    setFailContinuous(false);
                } catch (SQLException e) {
                    LOG.error("create connection SQLException, url: " + jdbcUrl + ", errorCode " + e.getErrorCode()
                              + ", state " + e.getSQLState(), e);

                    errorCount++;
                    if (errorCount > connectionErrorRetryAttempts && timeBetweenConnectErrorMillis > 0) {
                        // fail over retry attempts
                        setFailContinuous(true);
                        if (failFast) {
                            lock.lock();
                            try {
                                notEmpty.signalAll();
                            } finally {
                                lock.unlock();
                            }
                        }

                        if (breakAfterAcquireFailure) {
                            break;
                        }

                        try {
                            Thread.sleep(timeBetweenConnectErrorMillis);
                        } catch (InterruptedException interruptEx) {
                            break;
                        }
                    }
                } catch (RuntimeException e) {
                    LOG.error("create connection RuntimeException", e);
                    setFailContinuous(true);
                    continue;
                } catch (Error e) {
                    LOG.error("create connection Error", e);
                    setFailContinuous(true);
                    break;
                }

                if (connection == null) {
                    continue;
                }

                boolean result = put(connection);
                if (!result) {
                    JdbcUtils.close(connection.getPhysicalConnection());
                    LOG.info("put physical connection to pool failed.");
                }

                errorCount = 0; // reset errorCount
            }
        }
    }
登入後複製

這是一個多線程的類,而run 方法裡面設置了沒有限制的for 循環for (;;) {}, 而日誌報錯定位的信息:

connection = createPhysicalConnection();
登入後複製

如果符合條件errorCount > connectionErrorRetryAttempts && timeBetweenConnectErrorMillis > 0 會再嘗試重連,先看一下這幾個參數的意義:

errorCount 錯誤次數

在run 方法初始化時為零,每次連線失敗,會自動加1

connectionErrorRetryAttempts

連接錯誤重試次數,預設值為1。

protected int  connectionErrorRetryAttempts  = 1;
登入後複製

timeBetweenConnectErrorMillis

#連線間隔時間,單位毫秒。預設值為 500。

protected volatile long timeBetweenConnectErrorMillis = DEFAULT_TIME_BETWEEN_CONNECT_ERROR_MILLIS;
public static final long DEFAULT_TIME_BETWEEN_CONNECT_ERROR_MILLIS = 500;
登入後複製

我們在連接資料庫失敗後,要不在裡面break 中斷,其中有

if (breakAfterAcquireFailure) {
     break;
}
登入後複製

將改變break-after-acquire-failure 設定成true,在application.properties 檔案如下設定:

spring.datasource.druid.break-after-acquire-failure=true
登入後複製

如果想多嘗試連接幾次,需要設定connection-error-retry-attempts ,當errorCount 大於connectionErrorRetryAttempts 才會進入到條件內,才會中斷循環。下面是 application.properties 檔案的設定:

spring.datasource.druid.connection-error-retry-attempts=3
登入後複製

以上是springboot druid資料庫連線池連線失敗後一直重連怎麼解決的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:yisu.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板