您的位置:首页 > 其它

使用 ReplicationConnection 连接 Master/Slave 实现负载均衡

2013-05-31 15:36 531 查看
从JDBC驱动程序Connector/J 3.1.7 开始,我们提供了一个JDBC驱动’变体’。它能够通过Connection.getReadOnly()返回的状态,自动向可读写的Master数据提交查询语句,进行错误恢复及在Slaver数据库集间实现负载均衡。

应用程序通过调用Connection.setReadOnly(true)将事务设为只读,这将使事务被提交到那些通过轮转调度实现负载均衡的Slave服务器上(这将连接到一个Slave服务器上,除非Slave已在服务器集上被移除)。如果你要进行数据更新操作,或者你要进行一个时间敏感的读操作(在MySql上Master/Slave 间的数据同步是同步进行的),你可以通过调用Connection.setReadOnly(false)将与数据库的连接后的数据操作设为不是只读,则驱动程序将确保此连接的后续操作被发送到Master数据库上进行操作。驱动程序通过检查当前的autocommit(只动提交)标记,隔离级别,以及维护所有的数据库连接列表来实现负载均衡的功能。

在配置数据库连接池或为单独的程序创建JDBC驱动实例时,你必须使用" com.mysql.jdbc.ReplicationDriver " 类以便让驱动自动实现Master和Slave间的负载均衡。ReplicationDriver使用与标准的JDBC 驱动相同的URL格式连接数据库,目前ReplicationDriver不能和标准的java.sql.DriverManager一起工作,ReplicationDriver并不是使用java.sql.DriverManager连接数据库的,仅仅是使用它注册MySql
JDBC 驱动程序而已。

下面是一个简短的示例程序用以说明如何在单独的应用程序中通过ReplicationDriver连接数据库进行数据操作:



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();




// 对Slave进行故障恢复


props.put("autoReconnect", "true");




// 在Slave上进行负载均衡


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"


//




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




.......


}


}

负载均衡JDBC连接池(lbpol)工具封装了标准的JDBC驱动,它允许你使用数据连接池并能够通过它检查系统故障及不均衡的负载分布。如果你有兴趣了解lbpol,请查看下面链接http://code.tailrank.com/lbpool

具体参照官方文档:http://dev.mysql.com/doc/refman/5.1/en/connector-j-reference-replication-connection.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: