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 出阁宴祝福语姐姐简短