当系统数据量发展到一定程度后,往往需要进行数据库的垂直切分和水平切分,以实现负载均衡和性能提升,而数据切分后随之会带来多数据源整合等等问题。如果仅仅从应用程序的角度去解决这类问题,无疑会加重应用程度的复杂度,因此需要一个成熟的第三方解决方案。
Amoeba正是解决此类问题的一个开源方案,Amoeba位于应用程序和数据库服务器之间,相当于提供了一个代理,使得应用程序只要连接一个Amoeba,相当于只是在操作一个单独的数据库服务器,而实际上却是在操作多个数据库服务器,这中间的工作全部交由Amoeba去完成。
本文针对基于MySQL的水平切分的实现机制,讲解Amoeba For MySQL的简单应用。
log4j:WARN log4j config load completed from file:D:\JavaTools\amoeba-mysql-binar
y-2.2.0\bin\..\conf\log4j.xml
2013-01-08 09:32:27,765 INFO context.MysqlRuntimeContext - Amoeba for Mysql cur
rent versoin=5.1.45-mysql-amoeba-proxy-2.2.0
log4j:WARN ip access config load completed from file:D:\JavaTools\amoeba-mysql-b
inary-2.2.0\bin\../conf/access_list.conf
2013-01-08 09:32:27,921 INFO net.ServerableConnectionManager - Amoeba for Mysql
listening on 0.0.0.0/0.0.0.0:8066.
2013-01-08 09:32:27,921 INFO net.ServerableConnectionManager - Amoeba Monitor S
erver listening on /127.0.0.1:40170. 2、连接Amoeba
通过mysql客户端连接Amoeba,端口指定为8066,然后还像以前操作MySQL一样进行操作:
D:\>mysql -P8066 -uroot -pchenfeng123
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 21616774 to server version: 5.1.45-mysql-amoeba-prox
y-2.2.0
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> 3、验证数据的查询
查询yunzhu库下的user_info表的数据,如下:
mysql> select * from yunzhu.user_info;
+--------+-----------+
| USERID | USERNAME |
+--------+-----------+
| 108 | Jiang Su |
| 200 | NanJing |
| 73 | Chen Feng |
| 88 | China |
+--------+-----------+
4 rows in set (0.02 sec)
可以看到,现在查到了两个数据库节点中的user_info表中的所有记录。
D:\>mysql -uroot -pchenfeng
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 33 to server version: 5.0.18-nt
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> select * from yunzhu.user_info;
+--------+-----------+
| USERID | USERNAME |
+--------+-----------+
| 55 | test55 |
| 73 | Chen Feng |
| 88 | China |
+--------+-----------+
3 rows in set (0.00 sec)
查询数据库节点2:
D:\>mysql -uroot -pchenfeng -h10.167.157.176
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 34 to server version: 5.0.18-nt
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> select * from yunzhu.user_info;
+--------+----------+
| USERID | USERNAME |
+--------+----------+
| 108 | Jiang Su |
| 155 | test155 |
| 200 | NanJing |
+--------+----------+
3 rows in set (0.00 sec)
可以发现USERID为55的记录插入到了数据库节点1中,USERID为155的记录插入到了数据库节点2中。
因为根据rule.xml中的切分规则,USERID小于等于100的的记录存在数据库节点1中,而大于100的则存在数据库节点2中。
四、注意一些限制
这是我在实践中发现的,刚开始不知道存在这样的限制,以致于浪费了很多时间,以为配置有问题,搞了很久才发现原来是因为这些限制才导致没有出现预期的结果,所以必须要注意:
1、不管是查询和插入,每条都必须显式地指定数据库名(yunzhu),否则只会从一个数据库节点中查询数据,或者所有数据全部会插入一个数据库节点中。
2、插入数据时,必须显式地指定列名,如“insert into yunzhu.user_info(USERID,USERNAME)”,否则切分规则不会生效,所有记录都会插入到一个数据库节点中。