前言
DriverManager.getConnection的目標是獲得一個Connection,而Connection的關鍵部分在於QueryExecutor
順序
DriverManager的getConnection的實現方法,實際上是對其儲存的每個"Driver"(實際並非直接儲存Driver型別引用)嘗試執行Driver.connect(url,info);
Driver.connect(url,info)方法,則是先將本地的配置資訊、url中攜帶的配置資訊組合到info(props)中,繼而執行Driver.makeConnection(url,props)獲得對應的Connection實現型別;
對於PG,Driver.makeConnection(url,props)呼叫PgConnection的構造方法:PgConnection(hostSpecs(props), props, url)。hostSpecs(props)從props(Properties物件)中解析出PostgreSQL資料庫的主機名、埠號以及本地套接字地址,並構建一一對應的陣列。
而PgConnection(hostSpecs(props), props, url)的關鍵在於this.queryExecutor = ConnectionFactory.openConnection(hostSpecs, info),獲得一個queryExecutor例項;
而ConnectionFactory.openConnectionImp(hostSpecs, info)的關鍵步驟在於:
- 根據info建立一個SocketFactory;
- 建立hostSpec--targetServerType對應關係陣列,對每個陣列進行遍歷:
- 執行ConnectionFactory.tryConnect(info, socketFactory, hostSpec, sslMode, gssEncMode)獲得一個new PgStream;
- ConnectionFactory.tryConnect(info, socketFactory, hostSpec, sslMode, gssEncMode)關鍵在於構建一個PGStream:PGStream(socketFactory, hostSpec, connectTimeout, maxSendBufferSize);
- PGStream(socketFactory, hostSpec, connectTimeout, maxSendBufferSize)關鍵在於新建一個socket,並建立該socket的輸入輸出流和緩衝區
- ConnectionFactory.tryConnect(info, socketFactory, hostSpec, sslMode, gssEncMode)關鍵在於構建一個PGStream:PGStream(socketFactory, hostSpec, connectTimeout, maxSendBufferSize);
- 使用QueryExecutorImpl(newStream, cancelSignalTimeout, info)構建所求的QueryExecutor;
- 執行ConnectionFactory.tryConnect(info, socketFactory, hostSpec, sslMode, gssEncMode)獲得一個new PgStream;