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"); ....... } }
感谢阅读,希望能帮助到大家,谢谢大对本站的支持!