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");
.......
}
}
感谢阅读,希望能帮助到大家,谢谢大对本站的支持!
热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短