分享一個MySQL ReplicationDriver類代碼
發(fā)表時間:2023-08-31 來源:明輝站整理相關(guān)軟件相關(guān)文章人氣:
[摘要]$velocityCount在 MySQL 復(fù)制的環(huán)境中,要通過 JDBC 連接這個 MySQL 集群,就必須使用 ReplicationDriver 這個類來替換原有的 com.mysql.jdbc.Driver 。不過該 Driver 在連接池環(huán)境下無效,要通過連接池連接 MySQL 集群可使...
在 MySQL 復(fù)制的環(huán)境中,要通過 JDBC 連接這個 MySQL 集群,就必須使用 ReplicationDriver 這個類來替換原有的 com.mysql.jdbc.Driver 。不過該 Driver 在連接池環(huán)境下無效,要通過連接池連接 MySQL 集群可使用 lbpool。
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");
props.put("user", "foo");
props.put("password", "bar");
//
// Looks like a normal MySQL JDBC url, with a
// comma-separated list of hosts, the first
// being the 'master', the rest being any number
// of slaves that the driver will load balance against
//
Connection conn =
driver.connect("jdbc:mysql://master,slave1,slave2,slave3/test",
props);
//
// Perform read/write work on the master
// by setting the read-only flag to "false"
//
//這個節(jié)點應(yīng)該是通過spring的事務(wù)管理來設(shè)置,同時這個conn對象應(yīng)該不是一個真正的connection,
//而是一個代理類,通過設(shè)置readonly,代理類會去使用不同的connection,
//那么問題是它該代理類使用的connection是哪里取的,抑或說難道它每次都會新開一個connection?,需要看源代碼
conn.setReadOnly(false);
conn.setAutoCommit(false);
conn.createStatement().executeUpdate("UPDATE some_table ....");
conn.commit();
//
// Now, do a query from a slave, the driver automatically picks one
// from the list
//
conn.setReadOnly(true);
ResultSet rs =
conn.createStatement().executeQuery("SELECT a,b FROM alt_table");
.......
}
以上就是分享一個MySQL ReplicationDriver類代碼的詳細內(nèi)容,更多請關(guān)注php中文網(wǎng)其它相關(guān)文章!
學習教程快速掌握從入門到精通的SQL知識。