mySql数据库如果采用复制(Replication)方式的群集,在程序中进行读写分离的处理办法有如下几种:
自动主从管理方案有: MHA 官方介绍:https://code.google.com/p/mysql-master-ha/
1、采用 MySql提供的 ReplicationDriver 驱动程序, 简单的过程如下:
缺点: 无法集成到 Spring 进行读写分离操作。
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");
.......
}
2、采用 多数据源方式配置, 如:配置写数据源, 读数据源, 在程序中选择使用。
#读数据源
DBDriver=com.mysql.jdbc.Driver
url=jdbc\:mysql\:loadbalance\://slave1,slave2,slave3\:3306/test?roundRobinLoadBalance\=true&characterEncoding\=UTF-8
name=test
pass=test
characterEncoding=utf8
#写数据源
DBDriver=com.mysql.jdbc.Driver
url=jdbc\:mysql\:loadbalance\://master\:3306/test?roundRobinLoadBalance\=true&characterEncoding\=UTF-8
name=test
pass=test
characterEncoding=utf8
3、Mysql Router
MySQL Proxy 是非 GPL 的, 所以选择 MySql Router ,
MySQL Router是一个轻量级的中间件,提供了应用程序与后端数据库的透明路由,是mysql用来实现负载均衡和高可用功能。
同时router也提供了使用fabric 高可用的方式。
配置中:
mode = read-only时,
客户端请求将被循环分发给配置列表,当配置列表中服务器不可用,将会跳过该服务器,
列表中下一个可用机器将处理请求,如列表没有可用服务器,路由将失败。
mode = read-write时,
所有客户端请求都会被列表中第一个可用服务器处理,当此服务器宕机时,
列表中下一个可用机器才会处理客户端请求,如列表没有可用服务器,路由将失败。
第一个被成功连接的服务器信息将被保存在内存中,重启router后失效。
这样可以通过 Router 访问 mysql , 这样做好像也没有什么明显的好处(除负载均衡外)。
4、下面的数据库中间件 可以 访问 读写分离的 mysql 数据库集群,摘录如下,以备查看。
A、Amoeba
百度知道地址: http://baike.baidu.com/link?url=N2uPirw5znkFAvFUh0PDLlRLy7flqfUNdJmsP6oNCm-ziGrFSxzX-H1_fnjJ1FmjGjyZ1daDPc_euxVwcg-OBq
从官网看, 最近一次更新在: Last Update: 2013-07-05
B、Mycat
http://www.mycat.org.cn/
国内最活跃的、性能最好的开源数据库中间件!
这个很活跃,国人的,请大力支持。
mysql集群的初步整理
猜你喜欢
转载自iwin.iteye.com/blog/2353304
今日推荐
周排行