BUG表現(xiàn)
測試同學(xué)反饋,配置錯了一個數(shù)據(jù)庫的IP地址,服務(wù)啟動沒有錯誤,沒有中止服務(wù)啟動,導(dǎo)致很難查問題,希望能加上報錯信息。
數(shù)據(jù)庫配置和網(wǎng)上配置差不多
spring.datasource.url=xxxx
spring.datasource.username=xxx
spring.datasource.password=xxx
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.initial-size=1
spring.datasource.druid.min-idle=1
spring.datasource.druid.max-active=40
spring.datasource.druid.max-wait=5000
spring.datasource.druid.time-between-eviction-runs-millis=60000
spring.datasource.druid.min-evictable-idle-time-millis=300000
spring.datasource.druid.validation-query=SELECT 1 FROM DUAL
spring.datasource.druid.validation-query-timeout=3
spring.datasource.druid.pool-prepared-statements=true
spring.datasource.druid.max-pool-prepared-statement-per-connection-size=20
第一階段解決
先將日志輸出,原來系統(tǒng)用的logback的配置,導(dǎo)致druid的錯誤日志沒有輸出
換成log4j.properties的配置解決。
看到報錯信息是:連接失敗。但是debug進(jìn)入的時候發(fā)現(xiàn)幾個新的問題:
1 druid配置沒有生效
2 連接失敗無限重試
3 初始化75s之后才會提示錯誤信息,而不是一開始就提示
第二階段解決
找到錯誤前第一段日志,定位到代碼中,下一個斷點
LOG.info("{dataSource-" + this.getID() + "} inited");
順便看到我們用的druid版本是:1.0.18
找到DruidDataSource的構(gòu)造方法:
Springboot自動注入會預(yù)加載對象,看到其中System.getProperties(),加個斷點,
這里只是將系統(tǒng)變量注入,沒有我們配置的屬性,問題的關(guān)鍵不在這里。
public DruidDataSource(boolean fairLock){
super(fairLock);
configFromPropety(System.getProperties());
}
然后一路Debug下去,找到了Druid獲取連接的代碼
@Override
public DruidPooledConnection getConnection() throws SQLException {
return getConnection(maxWait);
}
這里的maxWait是-1,不是我們配置的max-wait,是第一個問題。
但是這里注入了數(shù)據(jù)庫的url,name和password信息
輔助信息:
debug過程中,看到@PostConstruct注入的類之前,已經(jīng)有了數(shù)據(jù)庫的
url,name和password信息
所以知道application.properties中數(shù)據(jù)庫的url,name,password相關(guān)信息
實在Springboot啟動時已經(jīng)注入了。
ps: 這里需要一點Springboot AutoConfigure相關(guān)知識,這里就不補充了,
簡單來說,springboot的autoconfigure會去讀meta-inf/metadata.json的內(nèi)容,根據(jù)其中內(nèi)容進(jìn)行自動配置。
搜索了一下,
我們用的springboot版本下確實有相關(guān)信息:
{
"name": "spring.datasource.username",
"type": "java.lang.String",
"description": "Login user of the database.",
"sourceType": "org.springframework.boot.autoconfigure.jdbc.DataSourceProperties"
}
但是沒有:
spring.datasource.druid.*
相關(guān)信息
問題找到了,是我們用的配置不對,導(dǎo)致application.properties中的配置沒有生效。
在網(wǎng)上搜了一下,在pom.xml中添加
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
這樣配置druid的配置才能生效。
無限重連:
在druid 1.0.18中,其實不是無限次,是30次,只是給我們感覺是無限次
protected int connectionErrorRetryAttempts = 30;
升級到1.1.10解決了這個問題,因為他的配置是
protected int connectionErrorRetryAttempts = 1;
最后一個問題,為什么啟動的時候連接是1分15秒之后報錯。
這個我們對于connect連接進(jìn)行debug,發(fā)現(xiàn)并沒有設(shè)置超時時間,或者說我們設(shè)置的超時時間是0。
這里的過程比較長,我直接說結(jié)論吧。
Connect的建立過程,
1 先嘗試druid connect
conn = createPhysicalConnection(url, physicalConnectProperties)
一個責(zé)任鏈來判斷druid中誰可以創(chuàng)造連接
if (this.pos < filterSize) {
return nextFilter()
.connection_connect(this, info);
}
Driver driver = dataSource.getRawDriver();
String url = dataSource.getRawJdbcUrl();
2 因為我們的配置錯誤,所以走到了:dataSource.getRawDriver()
利用了原始的mysql-connector
Connection newConn = com.mysql.jdbc.ConnectionImpl.getInstance(host(props), port(props), props, database(props), url);
3 其中使用的JDBC connect
return (Connection) Util.handleNewInstance(JDBC_4_CONNECTION_CTOR,
new Object[] { hostToConnectTo, Integer.valueOf(portToConnectTo), info, databaseToConnectTo, url }, null);
4 一番檢查和初始化之后MysqlIO,這其中創(chuàng)建的是一個socket連接
this.io = new MysqlIO(newHost, newPort, mergedProps, getSocketFactoryClassName(), getProxy(), getSocketTimeout(),
this.largeRowSizeThreshold.getValueAsInt());
通過一個工廠類創(chuàng)建socket連接
this.mysqlConnection = this.socketFactory.connect(this.host, this.port, props);
5 又是一番socket的初始化和配置之后,底層調(diào)用
synchronized void doConnect(InetAddress address, int port, int timeout) throws IOException {
synchronized (fdLock) {
if (!closePending && (socket == null || !socket.isBound())) {
NetHooks.beforeTcpConnect(fd, address, port);
}
}
try {
acquireFD();
try {
socketConnect(address, port, timeout);
/* socket may have been closed during poll/select */
synchronized (fdLock) {
if (closePending) {
throw new SocketException ("Socket closed");
}
}
// If we have a ref. to the Socket, then sets the flags
// created, bound & connected to true.
// This is normally done in Socket.connect() but some
// subclasses of Socket may call impl.connect() directly!
if (socket != null) {
socket.setBound();
socket.setConnected();
}
} finally {
releaseFD();
}
} catch (IOException e) {
close();
throw e;
}
}
其中:socketConnect是一個native方法,我們就不繼續(xù)向下看了。一個默認(rèn)的初始化連接超時時間在系統(tǒng)底層設(shè)置。
native void socketConnect(InetAddress address, int port, int timeout)
throws IOException;
其他
- 查這個問題之后有個經(jīng)驗,配置更優(yōu)的工程實踐還是自己在項目中寫一個Config.java文件,Springboot可以通過加入@Configuration的方式注入,
可以屏蔽不同的版本差異,配置也更可控。
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean(name = "dataSource")
public DataSource druid(){
return new DruidDataSource();
}
}