欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

MySQL 读写分离实例详解

程序员文章站 2023-12-18 08:19:46
mysql 读写分离 mysql读写分离又一好办法 使用 com.mysql.jdbc.replicationdriver 在用过amoeba 和 cobar,还有db...

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");
 
   .......
 }
}

感谢阅读,希望能帮助到大家,谢谢大对本站的支持!

上一篇:

下一篇: