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 送给学长毕业祝福语简短