DB數據源之SpringBoot+MyBatis踏坑過程(四)沒有使用鏈接池的後果html
liuyuhang原創,未經容許禁止轉載 mysql
系列目錄鏈接spring
DB數據源之SpringBoot+Mybatis踏坑過程實錄(一)sql
1.環境說明數據庫
1.1.使用springboot手動獲取數據源,其中數據源DataSource使用以下代碼獲取:編程
1 DataSourceBuilder create = DataSourceBuilder.create(); 2 ... 3 4 DataSource source = create.build();
1.2.只使用了這種方式來建立數據源,而且沒有配置數據源鏈接池tomcat
1.3.在springboot1.0中沒有配置tomcat數據源鏈接池springboot
1.4.在springboot2.0中沒有配置tomcat數據源鏈接池,也沒有配置HikariCP鏈接池app
2.報錯表現post
2.1.部分報錯內容以下:
Error querying database. Cause: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
Cause: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet successfully received from the server was 14,595,596 milliseconds ago. The last packet sent successfully to the server was 14,595,612 milliseconds ago.
2.2.或部分報錯內容以下:
o.a.tomcat.jdbc.pool.ConnectionPool : Unable to create initial connections of pool.
Data source rejected establishment of connection, message from server: "Too many connections"
2.3.在報錯內容中,有關於鏈接池的類,springboot1.0中會出現tomcat的鏈接池,springboot2.0中會出現Hikari的鏈接池這兩種錯誤。
2.4.數據庫中現存的鏈接數量會持續上漲,一直到上漲閾值。查看方法以下:
cmd-->鏈接mysql數據庫-->輸入show status like 'Threads%',結果可能以下:
其中Threads_connected的數量就是上文提到的現存的鏈接數量,若是配置了鏈接池,在不斷對數據庫發送請求的時候,
該數量雖然會上漲,可是停下來會有消退,同時上漲速度不會那麼快的。
能夠持續刷新服務發送請求,而後不斷使用此命令查看連接變化,達到某個數字之後,若是報錯了,那麼查看mysql設置。
該設置應該在mysql根目錄中,或者是mysql的data所在目錄下,名爲my.ini的配置文件,其中有配置最大連接數量,
可進行調整。
3.緣由分析
有兩種寫法實際上中間是有問題的,寫法和問題緣由以下:
1 //使用DataSourceBuilder得到數據源額建立者過程當中,DataSourceBuilder是有泛型指定的,該泛型沒有指定 2 //create只能夠對url,driverClassName,username,password進行設置,並無相關鏈接池配置 3 DataSourceBuilder<?> create = DataSourceBuilder.create(); 4 DataSource source1 = create.build(); 5 //使用DataSourceBuilder得到數據源建立的過程當中,使用額是鏈式編程 6 DataSource source2 = DataSourceBuilder.create().build(); 7 8 //DataSource是一個接口,並不是實際的類,所以能set的設置項很是少 9 public interface DataSource extends CommonDataSource, Wrapper
因爲上述代碼只定義了連接屬性,並無定義鏈接池,而mysql數據庫能夠維持的鏈接數量有限,因此致使本文所指錯誤。
4.解決方案
對於springboot2.0如下的版本,可考慮額外配置一個tomcat鏈接池
對於springboot2.0以上的版本,可考慮額外配置一個tomcat鏈接池以外,還能夠配置使用HikariCP鏈接池
具體手動配置方案,下次在更!
以上