public class ReplicationDriverDemo { //開源軟件:phpfensi.com public static void main(String[] args) throws Exception { ReplicationDriver driver = new ReplicationDriver();
Properties props = new Properties();
// We want this for failover on the slaves props.put("autoReconnect", "true");
// We want to load balance between the slaves props.put("roundRobinLoadBalance", "true");
jdbc:mysql:replication: //master:3306,slave1:3306,slave2:3306/dbname When using the following connection string: jdbc:mysql:replication://dbmaster:3306,dbslave1:3306,dbslave2:3306/dbname dbmaster is used for all write connections as expected and dbslave1 is used for all read connections, but dbslave2 is never used. I would have expected distributed reads between dbslave1 and dbslave2. 原理是:ReplicationDriver生成代理的connection對象,當設置這個connection.readOnly=true時,連接slave,當connection.readOnly=false時,連接master.
負載均衡:
jdbc:mysql:loadbalance: //master:3306,slave1:3306,slave2:3306/dbname When using the following connection string: jdbc:mysql:loadbalance://dbmaster:3306,dbslave1:3306,dbslave2:3306/dbname connections are load-balanced between all three servers for both read and write connections. 問題:讀寫分離時可能會碰到剛寫完master,再馬上到slave進行查詢的情況,而主從復制的時候有延遲,這時怎么解決呢?有兩個辦法: