jdbc.psotgresql學習3

wotrd發表於2017-12-15

Connection Parameters:
PreapareThresHold: 確定PreparedStatement切換到使用伺服器端預處理語句之前所需的執行次數。意思是在同一個PreparedStatement物件的第五次執行中使用伺服器端預處理語句。設定為小於0是為1,表示每次都使用快取中的。等於0的話為0,表示不使用快取。預設值是5。結果如下:

判斷是否使用threshold:

PGConnection的構造方法中開始設定。

設定PrepareThreshold。

在PgStatement類的executeInternal 中呼叫isOnwShotQuery方法判斷是否執行一次。

ForceBinary:如果threshold小於0forcebinarytransfer為true;

preferQueryMode = String指定使用哪種模式執行對資料庫的查詢:簡單模式(`Q`執行,不解析,不繫結,僅文字模式),擴充套件表示總是使用繫結/執行訊息,extendedForPrepared表示僅擴充套件用於預處理語句,extendedCacheEverything表示使用擴充套件協議並嘗試快取查詢快取中的每個語句(包括Statement.execute(String sql))。擴充套件| extendedForPrepared | extendedCacheEverything | 簡單預設是擴充套件的。
在QueryExcecutorBase中有:對queryexecutor進行初始化:

在PgConnection中有方法:

在QueryExcetorImp中有方法在execute中會提前呼叫:

在PgStatement中有:

loadBalanceHosts = Boolean: 需要先在url中加上loadBalanceHosts=true代表開啟負載均衡。也就是如下配置url:
:postgresql://node1,node2,node3/accounting?targetServerType=preferSlave&loadBalanceHosts=true
在Driver類中parseURL方法首先會解析主機節點到引數properties中,此時info中有多個主機節點地址:

在Driver類的hostSpecs方法中,會將props配置檔案中節點資訊賦值給hostspc物件然後執行PGConnection構造方法:

在ConnectionFactoryImpl的openConnectionImpl方法中首先獲取url引數中的targetServerType資訊。沒有的話賦值為any

在這個方法中建立HostChooser就是一個遍歷主機的迭代器

叢集的話需要加上servertype,在物件中加上要連線的目標主機的型別。

然後在while迴圈中開始對每個節點遍歷建立PgStream:

判斷目標主機的servertype:

目標主機和引數主機不一致拋異常:

最後在連線池中選出一個連線進行連線:返回一個queryexecuter

ssl:安全套接字連線:Connect using SSL. The driver must have been compiled with SSL support. This property does not need a value associated with it. The mere presence of it specifies a SSL connection. However, for compatibility with future versions, the value “true” is preferred. For more information see Chapter 4, Using SSL安全協議SSL,利用資料加密、身份驗證和訊息完整性驗證機制,為網路上資料的傳輸提供安全性保證。支援各種應用層協議。SSL客戶端必須驗證SSL伺服器的身份,SSL伺服器是否驗證SSL客戶端的身份,則由SSL伺服器決定。通過ca證照,伺服器端向客戶端傳送證照,包含祕鑰等伺服器資訊,客戶端通過證照驗證伺服器身份,伺服器端不必須驗證客戶端身份。

主要使用方式:https、sslvpn

在ConnectionFactoryImpl的openConnectionImpl方法中開始設定:

defaultRowFetchSize = int:預設行抓取大小,在PGConnection的建構函式中設定。預設為從伺服器一次取出所有資料放在客戶端記憶體中,fetch size引數不起作用。在core.v3包的QueryExecutorImp類的sendOneQuery方法中有:

得讓(flags & QueryExecutor.QUERY_FORWARD_CURSOR) != 0為true。

如果connection是自動提交事務的,那麼,fetchSize將失效statement不是TYPE_FORWARD_ONLY的,那麼,fetchSize也將失效。

currentSchema = String:設定查詢的search_path來決定查詢那個schema下的表。
在ConnectionFactoryImpl的openConnectionImpl方法中設定只是在當前會話連線中將search_path改了連線斷開後失效。使用psql連線也是一次會話,要是search_path真正修改需要修改配置檔案。

cancelSignalTimeout = int(從9.4.1209開始)取消命令是通過自己的連線帶外傳送的,所以取消訊息本身可能會卡住。該屬性控制用於取消命令的“連線超時”和“套接字超時”。超時時間以秒為單位指定。預設值是10秒。
在ConnectionFactoryImpl的openConnectionImpl方法中設定:

tcpKeepAlive = boolean 啟用或禁用TCP保持活動狀態探測。預設是false。在ConnectionFactoryImpl的openConnectionImpl方法中設定

readOnly = Boolean Put the connection in read-only mode只讀模式
在PgConnection建構函式中設定

loginTimeout=int:指定等待建立資料庫連線的時間。超時時間以秒為單位指定。如果loginTimeout<=0,走在Driver類的connect方法中makeConnection()方法.反之,開啟ConnectThread設定完計時執行緒,再呼叫makeConnection方法。

ConnctThread內部類實現了Runnable介面。在返回conn的時候加了鎖保證執行緒安全。

用來返回result(Connection)物件。

targetServerType:主要在loadbalance中用到,用來說明客戶端請求連線是master或slave。但是單機使用slave會報異常如下,具體參考loadbalancehost引數:

執行過程:
首先Class.forName(driver);
呼叫Driver類的靜態程式碼塊,進行初始化。

呼叫register方法將Driver進行註冊

然後,呼叫獲取連線
DriverManager.getConnection(url,user,pwd);
走的是

PgConnection的建構函式開始執行

建立QueryExecutor物件

用來實現叢集

queryExecutor已經獲取完畢,也就是連線獲取成功現在開始執行操作。
Statement:
Connection呼叫createStatement方法獲取Statement物件。

呼叫PgStatement的建構函式進行初始化

PgStatement物件獲取成功,現在開始執行操作呼叫execute方法

IsOneShotQuery是threshold的方法

函式操作:
自定義函式:
參照https://jdbc.postgresql.org/d…
upper(””):將字串轉成大寫

count():求記錄數

Jdbc函式呼叫:
呼叫add方法可以通過call呼叫,也可以查詢呼叫,如下:

CallableStatement執行過程:
繼承了preparestatement所以preparestatement的方法都能執行。

conn執行prepareCall(sql)方法:

在建立CachedQuery之後,與PrepareStatement或Statement一致

注意事項:
1:通過AtomicInteger實現執行緒安全 reference是引用的意思。

2:Java安全許可權機制,通過AccessController授予許可權
    AccessController.doPrivileged()
3:maven的使用方法mvn + clean/build/install
4:ssl的使用方式

在centos6有的系統安裝pg10會在配置加上OpenSSL編譯make時出現如下錯誤,無法正確安裝:

然後再make clean出現系統錯誤。這個錯誤可能是某個linux系統原因:在configure之前使用make clean 命令可以正確安裝,configure之後,make錯誤在使用make clean出現系統錯誤。在其他系統中正常。

首先需要安裝gcc,gcc-c++,zlib,realine,make等依賴包還有devel包。資料庫開啟ssl必須在資料庫配置(configure)中加上OpenSSL才可以,命令為:

configure –prefix=address –with-openssl
資料庫安裝見地址:https://www.cnblogs.com/linhp…
然後,在正確安裝之後,配置開始配置ssl,配置ssl地址:
http://blog.csdn.net/zhu46745…
此時,伺服器已經配置成功。接下來,開始採用jdbc連線:
ssl有雙向和單向驗證,這裡我們資料庫採用單向驗證也就是隻有伺服器資料庫進行驗證,客戶端不用驗證。採用jdbc連線資料庫時只需要在url中加上ssl=true這條引數,開始連線但是你可能會遇到:
這條異常資訊無法正確連線,因為客戶端也就是jdbc需要驗證伺服器的證照。接寫來我們可以加上這條命令跳過驗證。當然,加上該條命令的話安全性肯定會降低。
&sslfactory=org.postgresql.ssl.NonValidatingFactory
如果不用跳過的驗證的話我們就需要採用

    
5:readme.md檔案包含了專案的解釋和連線引數(properties),contributing.md主要解釋如何分享專案
6:volatile在這裡可以做到的作用是使得多個執行緒可以共享變數,但是問題在於使用volatile將使得VM優化失去作用,導致效率較低,
7:Driver類中的connect方法和DriverManager中的getConnection方法區別:DriverManager中的getConnection方法呼叫了Driver中的connect方法。
8:void setPrepareThreshold(int threshold):預處理設定閾值
9:MetaData(後設資料):資料分為資料和後設資料,資料主要是檔案本身例如文字中的資料,後設資料是針對於系統,例如文字的存放地址,大小等,系統通過    後設資料管理文字資料。
10:osgi:open service gateway initial 面向Java的動態模型系統
11:SQLPermission 
12:setForceBinary:布林型別的,
13:setPrepareThreshold :PrepareThreshold預設值為5,是PreparedStatement的sql語句執行超過5次之後,使用已經存在的匹配的一句執行,提高速度。當然,也可以設定為禁止模式。可以稱之為臨界值。
14:PgStatement類中execute和executeUpdate方法區別:

兩者在底層呼叫的方法是一樣的,只不過返回值不同,execute返回的是布林型表示是否執行成功,executeUpdate表示更新解過返回最後改變的列數整形。使用executeUpdate進行增刪改, execute用來生成表和刪除表,

查詢走的底層方法也一樣:query返回的是resultset。

15java spi機制,簡單說就是定義一個介面,和幾個具體實現類。在classpath路徑下建立service資料夾,資料夾了建立介面路徑到類名字的檔案,檔案中定義實現類的路徑到類名,然後,通過serviceloader就可以將介面的具體實現類全部獲取出來。在jdbcDriver中有應用。

驅動載入和引數設定到例項化PGConnection物件過程:

Transaction: 事務應該具有4個屬性:原子性、一致性、隔離性、永續性。這四個屬性通常稱為ACID特性。
原子性(atomicity)。一個事務是一個不可分割的工作單位,事務中包括的諸操作要麼都做,要麼都不做。
一致性(consistency)。事務必須是使資料庫從一個一致性狀態變到另一個一致性狀態。一致性與原子性是密切相關的。
隔離性(isolation)。一個事務的執行不能被其他事務干擾。即一個事務內部的操作及使用的資料對併發的其他事務是隔離的,併發執行的各個事務之間不能互相干擾。
永續性(durability)。持續性也稱永久性(permanence),指一個事務一旦提交,它對資料庫中資料的改變就應該是永久性的。接下來的其他操作或故障不應該對其有任何影響。
autosave = String:指定查詢失敗時驅動程式應執行的操作
在autosave=always模式中,JDBC驅動程式在每個查詢之前設定一個儲存點,並在發生故障時回滾到該儲存點。在autosave=never模式下(預設),沒有儲存點回滾。在autosave=conservative模式中,為每個查詢設定儲存點,但是隻有在“快取語句不能更改返回型別”或“語句XXX無效”這樣的極少數情況下才執行回滾,因此JDBC驅動程式回滾並重試,預設是never,此操作一般在增刪改中使用。
呼叫過程:
首先,設定autocommit為false;

在execute方法中:

2.5.2 外連線
外連線返回的查詢結果集合中的不僅包含符合連線條件的行,而且還包括左表(左外連
接時)、右表(右外連線時)或兩個邊接表(全連線)中的所有資料行。
注意:對於外連線,oracle 可以使用“(+)”來表示。但 HighGo DB 資料庫不支援,所
以在 oracle 向 HighGo DB 資料庫遷移的時候,需要特別注意。

2.5.2 外連線
外連線返回的查詢結果集合中的不僅包含符合連線條件的行,而且還包括左表(左外連
接時)、右表(右外連線時)或兩個邊接表(全連線)中的所有資料行。
注意:對於外連線,oracle 可以使用“(+)”來表示。但 HighGo DB 資料庫不支援,所
以在 oracle 向 HighGo DB 資料庫遷移的時候,需要特別注意。

except差集oracle中使用的是minux
select from student except select from user;

序列是 HighgoDB 的一種特殊計算器,它由使用者建立,由系統管理。建立一個序列後,
可以將其作為某個欄位的預設值。在 insert 命令的執行期間,序列的值會被自動生成,並作為
資料行的唯一性編號,存放在該資料行相應的欄位中。

可以使用選項 config_file,hba_file,ident_file 分別宣告配置文
件的路徑。config_file 只能在 postgres 命令列上設定,但是其它的可以在主配置
檔案裡設定。如果明確設定了所有三個選項和 data_directory,那麼就沒必要宣告
-D 或 PGDATA。

如果你發現有”Too many open files”這樣的失敗現象,那麼就嘗試
縮小這個設定。這個值只能在伺服器啟動的時候設定max_files_per_process(integer)

Postgresql配置遠端連線
配置highgosql遠端連線的時候,將postgres.conf開啟監聽為*;然後修改pg_hba.conf 將ipv4設定為0.0.0.0/0 md5。允許外部接入。重新啟動服務。然後在bin目錄下使用./psql –h address 登入驗證是否成功。在配置完之後,配置防火牆,開啟5432埠。

包結構分析以及maven打包:
jdbc.postgresql學習:首先看readme和contributing檔案

Maven打jar包方式:jdbc通過maven進行jar包編譯:詳細見contributing.md檔案,搜尋mvn package在命令列中進入專案根目錄下(包含pom檔案的目錄),使用mvn package命令進行打包,在打包的過程中會進行測試,如果測試不通過的話,使用mvn package -DskipTests或mvn package -Dmaven.test.skip=true命令跳過測試直接進行編譯.即可成功。兩個命令的區別是:前者只進行編譯不進行檢查,後者既不檢查也不編譯

進入jre7或6目錄進行打包。
配置mvn庫的toolchains檔案:(不是專案的)

Jdbc.postgresql原始碼需要修改的地方:
1, 將埠改為: 5586

2, 驅動改為com.highgo.jdbc.

3, 包名改為:com.highgo.jdbc

4, 修改pom檔案:

5, 改一下證照:

1載入驅動:

通過Class.forName("驅動(Driver類)")方法將Driver類載入進記憶體,Driver類中的靜態程式碼塊執行初始化操作。使用DriverManager(期望載入儘可能多的驅動)中的registerDriver()方法,將Driver類進行註冊,每次註冊之前先判斷Driver是否已經註冊,有的話丟擲異常。沒有正常註冊

2分析外層類和外層包結構:
它們都是在org.postgresql目錄下的,最外層有Driver、PGConnection,PGnotification,PGProperty,PGRefCursorResultSet,PGResultSetMetaData,PGstatement類和copy,core,ds,fastpath,geometric,gss,hostchosser,jdbc,jdbc2,jdbc3,largeobject,osgi,replication,ssl,sspi,translation,util,xa包
外層類:
Driver:
1.當使用Class.forName()將驅動載入進記憶體後,Driver類中的靜態程式碼塊開始執行register方法進行初始化操作,register方法先判斷是否已經註冊,有的話丟擲異常返回,沒有開始註冊。並且賦值給自己的Driver方便驗證是否已經註冊。

2.其中用到SharedTimer類,進行資料庫連線計數操作。
3.使用getDefaultProperties方法載入預設的配置檔案,其中使用AccessController.doPrivileged意思是這個是特別的,不用做許可權檢查. 
4.loadDefaultProperties方法用來載入本地檔案,
5.connect方法:首先檢查主機地址是否正確錯誤返回。然後,獲取本地引數檔案並且做一個副本,遍歷connect中info引數,將不為空的加到本地引數檔案中,接著,使用parseURL方法將url地址解析然後新增到properties檔案中,沒問題的話,在執行timeout超時方法,小於0的話執行makeConnection進行連線,反之,執行ConnectionThread連線執行緒內部類。
 6.makeConnection方法:執行PGConnection的構造方法進行連線。
 7.deregister方法關閉連線
 8.ConnectionThread內部類實現了runnable:在連線超時的時候呼叫,通過建構函式進行初始化,將重連程式碼放到run方法中。

PGConnection:頂層Connection介面。主要是對sql.Connection介面方法的擴充套件。被BaseConnection介面所繼承。

PGNotification[] getNotifications():獲取通知
CopyManager getCopyAPI():copy管理者
LargeObjectManager getLargeObjectAPI() 大物件管理
Fastpath getFastpathAPI()    獲取FastPath
void addDataType(String type, String className);新增資料型別
void setPrepareThreshold(int threshold);    設定閾值
void setDefaultFetchSize(int fetchSize)    :設定預設抓取大小
int getDefaultFetchSize();獲得預設抓取大小
PGReplicationConnection getReplicationAPI();

PGNotification:頂層介面,This interface defines the public PostgreSQL extension for Notifications

String getName();獲取通知名字
int getPID();獲取通知執行緒id
String getParameter();    獲取通知引數

PGProperty:本類是一個列舉類,主要是資料庫的連線引數,例如(資料庫名字,埠,主機地址,使用者名稱,密碼,ssl,連線超時,登入超時)等引數。
PGRefCursorResultSet: As of 8.0, this interface is only present for backwards- compatibility purposes. New code should call getString() on the ResultSet that contains the refcursor to obtain the underlying cursor name.

PGResultSetMetaData:一個頂級介面:後設資料
String getBaseColumnName(int column) 獲取基本列的名字

     String getBaseTableName(int column) 獲取基本表的名字
     String getBaseSchemaName(int column) 獲取基本模式的名字
     int getFormat(int column) 獲取基本格式的名字

PGstatement:This interface defines the public PostgreSQL extensions to java.sql.Statement. All Statements constructed by the PostgreSQL driver implement PGStatement.
method:
long getLastOID() 返回上一個物件的 oid

void setPrepareThreshold(int threshold)
void setUseServerPrepare(boolean flag) 等同於void setPrepareThreshold(int threshold):設定閾值,
boolean isUseServerPrepare();    服務是不是使用了Prapare操作也就是threshold
int getPrepareThreshold();        預先獲取閾值

外層包:
copy:
core:

Version: Get a machine-readable version number.
ServerVersion :enum 類Enumeration for PostgreSQL versions.實現了Version
ConnectionFactory:一個抽象類。Handles protocol-specific connection setup.
     public static QueryExecutor openConnection(HostSpec[] hostSpecs, String user,String database, Properties info) 獲得查詢執行者
     public abstract QueryExecutor openConnectionImpl(HostSpec[] hostSpecs, String user,String database, Properties info) 

BaseConnection:Driver-internal connection interface. Application code should not use this interface. 繼承了PGConnection 和 Connection介面。被jdbc包下的PgConnection類所實現。也就是訪問PGConnection的物件最後將會轉到PGConnection中去執行。其實就是將返回的Connection物件指向PGConnection物件來執行具體的操作。BaseConnection以及Connection都將被PGConnection所實現。

     void cancelQuery() :取消查詢
     ResultSet execSQLQuery(String s)    執行查詢
     void execSQLUpdate(String s) 執行修改
     QueryExecutor getQueryExecutor() 獲得查詢執行者
     ReplicationProtocol getReplicationProtocol() 獲得副本協議
    Object getObject(String type, String value, byte[] byteValue)獲得物件PGobject} instance is returned.
     Encoding getEncoding() 獲得編碼
     TypeInfo getTypeInfo(); 獲得型別資訊
     boolean haveMinimumServerVersion(int ver);    獲得最小版本
     byte[] encodeString(String str) 編碼字串
     String escapeString(String str) 編譯字串
     boolean getStandardConformingStrings();是否獲得正確的字串
     TimestampUtils getTimestampUtils(); 獲得時間戳工具
     boolean getStringVarcharFlag(); 是否獲得varchar字串標籤
     TransactionState getTransactionState(); 獲得事務的狀態

SqlCommandType:Jdbc支援的sql命令。

     boolean binaryTransferSend(int oid);二進位制轉發
     boolean isColumnSanitiserDisabled();相同列消除
     void addTimerTask(TimerTask timerTask, long milliSeconds);新增時間任務
     void purgeTimerTasks();    肅清時間任務
     LruCache<FieldMetadata.Key, FieldMetadata> getFieldMetadataCache(); 獲得後設資料快取,採用LRU(last least used)最近最少使用演算法。                                 

CachedQuery createQuery(String sql, boolean escapeProcessing, boolean isParameterized,String… columnNames)有快取的查詢

     void setFlushCacheOnDeallocate(boolean flushCacheOnDeallocate); 設定解除分配記憶體的時候重新整理快取。

SocketFactoryFactory:Instantiates {@link SocketFactory} based on the {@link PGProperty#SOCKET_FACTORY}.獲取SocketFactory例項
PGStream:In general, instances of PGStream are not threadsafe; the caller must ensure that only one thread at a time is accessing a particular PGStream instance.
PgStream的構造方法如下圖:

PgStream中設定長度為4個位元組的位元組陣列,將整數先右移24位也就是3個位元組賦值給0,

BaseQueryKey:當ColumnNames

.v3:第3版本

ConnectionFactoryImpl:ConnectionFactory介面的實現類。ConnectionFactory implementation for version 3 (7.4+) connections.
private ISSPIClient createSSPI(PGStream pgStream, String spnServiceClass, boolean enableNegotiate) :
 public QueryExecutor openConnectionImpl(HostSpec[] hostSpecs, String user, String database,Properties info):

QueryExecutorImpl:QueryExecutor implementation for the V3 protocol.繼承了QueryExecutorBase

 public QueryExecutor openConnectionImpl(HostSpec[] hostSpecs, String user, String database,Properties info)
 private PGStream enableSSL(PGStream pgStream, boolean requireSSL, Properties info, int connectTimeout)

 private void sendStartupPacket(PGStream pgStream, List<String[]> params)
 private void doAuthentication(PGStream pgStream, String host, String user, Properties info)

認證主要是對密碼進行驗證,資料庫名和使用者名稱等已經傳送給資料庫系統了,在資料庫的data/pg_hbm.conf中對遠端登入進行設定,trust為沒有密碼MD5為需要密碼,從而在switch中走不同驗證方式。

 private void runInitialQueries(QueryExecutor queryExecutor, Properties info)
 private boolean isMaster(QueryExecutor queryExecutor) 

QueryExecutor:一個藉口查詢執行者
QueryExecutorBase:實現了QueryExecutor介面


VisibleBufferedInputStream:A faster version of BufferedInputStream. Does no synchronisation and allows direct access to the used byte[] buffer.

Encoding:Representation of a particular character encoding.

SetupQueryRunner:Poor man`s Statement & ResultSet, used for initial queries while we`re still initializing the system.
Utils: Collection of utilities used by the protocol-level code.
Oid: Provides constants for well-known backend OIDs for the types we commonly use.
ReplicationProtocol:Abstracts the protocol-specific details of physic and logic replication. With each connection open with replication options associate own instance ReplicationProtocol.
Provider:Represents a provider of results.

QueryWithReturningColumnsKey:Cache key for a query that have some returning columns. should contain non-quoted column names. The parser will quote them automatically.There`s a special case of {@code columnNames == new String[]{"*"}} that means all columns should be returned. {@link Parser} is aware of that and does not quote 

BaseQueryKey: This class is used as a cache key for simple statements that have no “returning columns”. Prepared statements that have no returning columns use just {@code String sql} as a key. Simple and Prepared statements that have returning columns use {@link QueryWithReturningColumnsKey} as a cache key.
Query:
CachedQuery:Stores information on the parsed JDBC query. It is used to cut parsing overhead when executing the same query through {@link java.sql.Connection#prepareStatement(String)}.
TypeInfo:
ds(DataSource):

fastpath:這是從java應用程式中執行嵌入後端的函式的一種手段。It is based around the file src/interfaces/libpq/fe-exec.c

Fastpath:
    

geometric:

gss:

hostchosser:
HostChooser:介面 Lists connections in preferred order.

    Iterator<HostSpec> iterator();

HostChooserFactory:Chooses a {@link HostChooser} instance based on the number of hosts and properties.建立一個主機選擇還是多個主機選擇(負載均衡中用到應該是叢集中的主備機)。

public static HostChooser createHostChooser(HostSpec[] hostSpecs,HostRequirement targetServerType, Properties info)

SingleHostChooser:實現了hostchooser介面 Host chooser that returns the single host.單一主機連線。

    public Iterator<HostSpec> iterator() 迭代主機
    public SingleHostChooser(HostSpec hostSpec)    建構函式進行初始化HostSpec集合使用Collections.singletonList()不可變連結串列儲存,只能儲存一個HostSpec物件,該物件包含主機地址和埠兩個屬性。

MultiHostChooser:實現了hostchooser介面 HostChooser that keeps track of known host statuses.多個主機進行連線區分master和slave主機用在負載均衡叢集上面。

    private int rank(HostStatus status, HostRequirement targetServerType) 目標主機的等級
    class HostSpecByTargetServerTypeComparator implements Comparator<HostSpecStatus> 實現了Comparator進行比較目標主機的等級

private List<HostSpec> extractHostSpecs(List<HostSpecStatus> hostSpecStatuses) 提取主機

    private void sortCandidates(List<HostSpecStatus> candidates) 對候選主機進行排序
    private void shuffleGoodHosts(List<HostSpecStatus> candidates) 打亂讓失去平衡。

GlobalHostStatusTracker :Keeps track of HostSpec targets in a global map.

private static final Map<HostSpec, HostSpecStatus> hostStatusMap = new HashMap<HostSpec, HostSpecStatus>(); 一個HostSpecMap。
    public static void reportHostStatus(HostSpec hostSpec, HostStatus hostStatus) :Store the actual observed host status.
    private static boolean updateStatusFromTo(HostStatus oldStatus, HostStatus newStatus) :驗證主機狀態是否為空或不是主或從機的話返回true,反之false;
    static List<HostSpecStatus> getCandidateHosts(HostSpec[] hostSpecs, HostRequirement targetServerType, long RecheckMillis) 獲得候選主機。Returns a list of candidate hosts that have the required targetServerType.

static class HostSpecStatus :Immutable(不可變的) structure of known status of one HostSpec.
在連線之前要求的連線目的主機型別

jdbc:
 PgConnection:BaseConnection的實現類:實現了PGConnection和Connection介面
Driver類的connect方法new一個PGConnection物件,通過構造方法物件PgConnection進行初始化,

    public void setDefaultFetchSize(int fetchSize) 設定預設抓取數量
    public int getDefaultFetchSize() 獲取預設抓取數量
public void setPrepareThreshold(int newThreshold) 設定預處理閾值臨界值
    public boolean getForceBinary() 獲取強制二進位制
    public void setForceBinary(boolean newValue)設定強制二進位制
    private final LruCache<FieldMetadata.Key, FieldMetadata> fieldMetadataCache; 
    public void execSQLUpdate(String s) :執行sql更新
    public java.sql.Statement createStatement() 建立statement通過PgStatement的建構函式初始化PgStatement,先呼叫checkClosed()方法
    public java.sql.PreparedStatement prepareStatement(String sql):通過過載呼叫PgPreparedStatement構造方法返回PreparedStatement例項。先呼叫checkClosed()方法。

Public CallableStatement prepareCall(String sql, int resultSetType, intresultSetConcurrency, int resultSetHoldability)

    public DatabaseMetaData getMetaData():獲取資料庫的後設資料,先呼叫checkClosed();該方法用來驗證ExecuterQuery是否已經關閉。
     
    private Set<Integer> getOidSet(String oidList):獲取Oid集合

public void close():關閉已經建立的連線。

   public void setReadOnly(boolean readOnly)設定只讀模式
 public void setAutoCommit(boolean autoCommit)設定是否自動提交。

手動提交:

public void rollback()設定回滾

public void setTransactionIsolation(int level):設定事務隔離。
設定查詢模式。
public CachedQuery createQuery(String sql, boolean escapeProcessing, boolean isParameterized,String… columnNames);

public boolean haveMinimumServerVersion(Version ver):獲取最小數量伺服器版本
private String oidsToString(Set<Integer> oids):將屬性名字變成字串
private void initObjectTypes(Properties info):// This initialises the objectTypes hash map

enum StatementCancelState:含有4中狀態。標誌statement物件的狀態。

  1. PgStatement:實現了BaseStatement和PGStatement介面。在PgConnection呼叫PgStatement的構造方法進行初始化物件獲取PgConnection的ForceBinary變數,並賦值給本例項中的變數,設定併發,結果集的型別,設定獲取值得大和PrepareThreadhold

FieldMetadata:This is an internal class to hold field metadata info like table name, column name, etc. This class is not meant to be used outside of pgjdbc.

TimestampUtils:Misc utils for handling time and date values.

TypeInfoCache:
public BaseConnection getPGConnection():獲取Connection例項
public int getFetchSize()

AutoSave:enum型別NEVER,  ALWAYS,  CONSERVATIVE; 

查詢執行:

public java.sql. ResultSet executeQuery(String p_sql):先執行executeWithFlags方法,在判斷resultset是否存在,存在的話返回給使用者。
Pgstatement執行過程:

Queryexecutor:在ConnectionFactory類的openConnection()方法中得到

connectionFactory.openConnectionImpl( hostSpecs, user, database, nfo);方法如下:在core.v3包中
首先判斷是否使用ssl
目標服務主機型別

在之前都是配置引數,獲取的socketfacroty。之後使用PgStream開始建立連線

jdbc2:

jdbc3:

largeobject:It provides methods that allow client code to create, open and delete large objects from the database. When opening an object, an instance of org.postgresql.largeobject.LargeObject is returned, and its methods then allow access to the object.

LargeObjectManager:

osgi:open service gateway initial 一個致力於解耦的模組控制使用jetty伺服器
replication:
PGReplicationConnection:僅當連線建立時需要複製屬性時,Api才可用PGProperty#REPLICATION}和PGProperty#ASSUME_MIN_SERVER_VERSION}。 沒有它的財產建立複製流失敗,例外。

public class MakeSSL extends ObjectFactory :converting regular socket connection to ssl
使用conver()將連線轉換成SSL模式的連線

public class LibPQFactory extends WrappedFactory implements HostnameVerifier :位於jdbc4包下,

sspi:

ISSPIClient:只允許windows系統的登入方式
boolean isSSPISupported(); 是否支援SSPI
void continueSSPI(int msgLength)  繼續使用SSPI
void startSSPI() 開始使用ssPI
void dispose(); 結束

translation(國際化):

util(工具包):

SharedTimer類: Incremented for each Timer created, this allows each to have a unique Timer name
其中使用到AtomicInteger(提供原子操作來進行Integer的使用,因此十分適合高併發情況下的使用)執行計數器。保證每個執行緒有自己的時間名字,它採用靜態AtomicInteger進行計數。
PSQLState 列舉類:This class is used for holding SQLState codes.

ObjectFactory:Helper class to instantiate objects. 使用反射機制例項化物件,即通過Class呼叫getConstructor方法,然後newInstance獲取例項,

CanEstimateSize:介面獲得建立時的大小。主要是用於後設資料的大小顯示。
LruCache<Key, Value extends CanEstimateSize>:Caches values in simple least-recently-accessed order.
ServerErrorMessage:
UnixCrypt:Contains static methods to encrypt and compare passwords with Unix encrypted passwords.

• MD5Digest:對使用者名稱和密碼進行雜湊值運算生成資訊摘要。Encodes user/password/salt information in the following way: MD5(MD5(password + user) + salt)

xa:

相關文章