MySQL 读写分离实例详解
MySQL读写分离
MySQL读写分离又一好办法使用com.mysql.jdbc.ReplicationDriver
在用过Amoeba和Cobar,还有dbware等读写分离组件后,今天我的一个好朋友跟我讲,MySQL自身的也是可以读写分离的,因为他们提供了一个新的驱动,叫com.mysql.jdbc.ReplicationDriver
说明文档:http://dev.mysql.com/doc/refman/5.1/en/connector-j-reference-replication-connection.html
代码例子:
importjava.sql.Connection;
importjava.sql.ResultSet;
importjava.util.Properties;
importcom.mysql.jdbc.ReplicationDriver;
publicclassReplicationDriverDemo{
publicstaticvoidmain(String[]args)throwsException{
ReplicationDriverdriver=newReplicationDriver();
Propertiesprops=newProperties();
//Wewantthisforfailoverontheslaves
props.put("autoReconnect","true");
//Wewanttoloadbalancebetweentheslaves
props.put("roundRobinLoadBalance","true");
props.put("user","foo");
props.put("password","bar");
//
//LookslikeanormalMySQLJDBCurl,witha
//comma-separatedlistofhosts,thefirst
//beingthe'master',therestbeinganynumber
//ofslavesthatthedriverwillloadbalanceagainst
//
Connectionconn=
driver.connect("jdbc:mysql:replication://master,slave1,slave2,slave3/test",
props);
//
//Performread/writeworkonthemaster
//bysettingtheread-onlyflagto"false"
//
conn.setReadOnly(false);
conn.setAutoCommit(false);
conn.createStatement().executeUpdate("UPDATEsome_table....");
conn.commit();
//
//Now,doaqueryfromaslave,thedriverautomaticallypicksone
//fromthelist
//
conn.setReadOnly(true);
ResultSetrs=
conn.createStatement().executeQuery("SELECTa,bFROMalt_table");
.......
}
}
感谢阅读,希望能帮助到大家,谢谢大对本站的支持!
热门推荐
10 广西考试祝福语结婚简短
11 猪年祝福语简短小孩
12 元旦祝福语送长辈简短
13 恭喜二宝祝福语简短
14 祝福语暖心话简短
15 国庆中秋祝福语简短兄弟
16 朋友订婚的祝福语简短
17 送弟弟中秋祝福语简短
18 爱生日祝福语简短独特