MySQL 讀寫分離執行個體詳解_Mysql

來源:互聯網
上載者:User

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

 代碼例子:

import java.sql.Connection;import java.sql.ResultSet;import java.util.Properties; import com.mysql.jdbc.ReplicationDriver; public class ReplicationDriverDemo {  public static void main(String[] args) throws Exception {  ReplicationDriver driver = new ReplicationDriver();   Properties props = new Properties();   // We want this for failover on the slaves  props.put("autoReconnect", "true");   // We want to load balance between the slaves  props.put("roundRobinLoadBalance", "true");   props.put("user", "foo");  props.put("password", "bar");   //  // Looks like a normal MySQL JDBC url, with a  // comma-separated list of hosts, the first  // being the 'master', the rest being any number  // of slaves that the driver will load balance against  //   Connection conn =    driver.connect("jdbc:mysql:replication://master,slave1,slave2,slave3/test",      props);   //  // Perform read/write work on the master  // by setting the read-only flag to "false"  //   conn.setReadOnly(false);  conn.setAutoCommit(false);  conn.createStatement().executeUpdate("UPDATE some_table ....");  conn.commit();   //  // Now, do a query from a slave, the driver automatically picks one  // from the list  //   conn.setReadOnly(true);   ResultSet rs =   conn.createStatement().executeQuery("SELECT a,b FROM alt_table");    ....... }}

感謝閱讀,希望能協助到大家,謝謝大對本站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.