分享一个MySQL ReplicationDriver类代码

零下一度
Lepaskan: 2017-04-25 17:45:55
asal
1146 orang telah melayarinya

在 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");
     .......
  }
Salin selepas log masuk

Atas ialah kandungan terperinci 分享一个MySQL ReplicationDriver类代码. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Label berkaitan:
sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!