分享一個MySQL ReplicationDriver類別程式碼

零下一度
發布: 2017-04-25 17:45:55
原創
1146 人瀏覽過

在MySQL 複製的環境中,要透過JDBC 連接這個MySQL 集群,就必須使用ReplicationDriver 這個類別來取代原有的com.mysql.jdbc.Driver 。不過此 Driver 在連線池環境下無效,要透過連線池連接 MySQL 叢集可使用 lbpool。

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://master,slave1,slave2,slave3/test",
            props);
    //
    // Perform read/write work on the master
    // by setting the read-only flag to "false"
    //
  //这个节点应该是通过spring的事务管理来设置,同时这个conn对象应该不是一个真正的connection,
	    //而是一个代理类,通过设置readonly,代理类会去使用不同的connection,
	    //那么问题是它该代理类使用的connection是哪里取的,抑或说难道它每次都会新开一个connection?,需要看源代码
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");
     .......
  }
登入後複製

以上是分享一個MySQL ReplicationDriver類別程式碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!