一:mysql读写分离原理

MySQL的主从复制和MySQL的读写分离两者有着紧密联系,首先部署主从复制,只有主从复制完了,才能在此基础上进行数据的读写分离。
简单来说,读写分离就是只在主服务器上写,只在从服务器上读,基本的原理是让主数据库处理事务性操作,而从数据库处理非事务性操作,然后再采用主从复制来把master上的事务性操作同步到slave数据库中。

1.基于程序代码内部实现
在代码中根据select,insert进行路由分类,这类方法也是目前生产环境应用最广泛的,优点是性能好,因为在程序代码中实现,不需要曾加额外的设备作为硬件开支,缺点是需要开发人员来实现,运维人员无从下手。
2.基于中间代理层实现
代理一般位于客户端和服务器之间,代理服务器接到客户端请求后通过判断后转发到后端数据库,有两个代表性程序。

(1)mysql-proxy 为mysql开源项目,通过其自带的lua脚本进行SQL判断,虽然是mysql的官方产品,但是mysql官方不建议将其应用到生产环境

(2)Amoeba (变形虫)由陈思儒开发,曾就职与阿里巴巴,该程序由java语言进行开发,阿里巴巴将其应用于生成环境,它不支持事物和存储过程

通过程序代码实现mysql读写分离自然是一个不错的选择,但是并不是所有的应用都适合在程序代码中实现读写分离,像一些大型复杂的java应用,如果在程序代码中实现读写分离对代码改动就较大,像这种应用一般会考虑使用代理层来实现。

二:基于 Amoeba 实现读写分离

amoeba

2.1 环境搭建

amoeba:192.168.2.203

masterDB:192.168.2.204

slaveDB:192.168.2.205
以上系统全为centos6.8

Amoeba框架是居于JDK1.5开发的,采用了JDK1.5的特性,所以还需要安装java环境,建议使用javaSE1.5以上的JDK版本

2.2 安装java环境

先去官网下载:http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

2.2.1 安装

[root@bogon src]# rpm -ivh jdk-8u111-linux-x64.rpm
Preparing...                ########################################### [100%]
   1:jdk1.8.0_111           ########################################### [100%]
Unpacking JAR files...
    tools.jar...
    plugin.jar...
    javaws.jar...
    deploy.jar...
    rt.jar...
    jsse.jar...
    charsets.jar...
    localedata.jar...

2.2.2 设置java环境变量

[root@bogon src]# vim /etc/profile

#set java environment
JAVA_HOME=/usr/java/jdk1.8.0_111
JRE_HOME=/usr/java/jdk1.8.0_111/jre
CLASS_PATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar:$JRE_HOME/lib
PATH=$PATH:$JAVA_HOME/bin:$JRE_HOME/bin
export JAVA_HOME JRE_HOME CLASS_PATH PATH
[root@bogon amoeba]# source /etc/profile

2.2.3 测试是否安装成功

[root@bogon src]# java -version
java version "1.8.0_111"
Java(TM) SE Runtime Environment (build 1.8.0_111-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.111-b14, mixed mode)

2.3 安装Amoeba

可以从https://sourceforge.net/projects/amoeba/下载最新版本的Amoeba,我这里下载的是amoeba-mysql-3.0.5-RC-distribution.zip。Amoeba安装非常简单,直接解压即可使用,这里将Amoeba解压到/usr/local/amoeba目录下,这样就安装完成了

[root@bogon amoeba]# pwd
/usr/local/amoeba
  [root@bogon amoeba]# ll
  总用量 20
  drwxrwxrwx. 2 root root 4096 7月 5 2013 benchmark
  drwxrwxrwx. 2 root root 4096 7月 5 2013 bin
  drwxrwxrwx. 2 root root 4096 7月 5 2013 conf
  -rwxrwxrwx. 1 root root 728 7月 5 2013 jvm.properties
  drwxrwxrwx. 2 root root 4096 7月 5 2013 lib

2.4 配置Amoeba

Amoeba的配置文件在本环境下位于/usr/local/amoeba/conf目录下。配置文件比较多,但是仅仅使用读写分离功能,只需配置两个文件即可,分别是dbServers.xml和amoeba.xml,如果需要配置ip访问控制,还需要修改access_list.conf文件,下面首先介绍dbServers.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
[root@bogon amoeba]# cat conf/dbServers.xml
<?xml version="1.0" encoding="gbk"?>
<!DOCTYPE amoeba:dbServers SYSTEM "dbserver.dtd">
<amoeba:dbServers xmlns:amoeba="http://amoeba.meidusa.com/">
<!--
Each dbServer needs to be configured into a Pool,
If you need to configure multiple dbServer with load balancing that can be simplified by the following configuration:
add attribute with name virtual = "true" in dbServer, but the configuration does not allow the element with name factoryConfig
such as 'multiPool' dbServer
-->
<dbServer name="abstractServer" abstractive="true">
<factoryConfig class="com.meidusa.amoeba.mysql.net.MysqlServerConnectionFactory">
<property name="connectionManager">${defaultManager}</property>
<property name="sendBufferSize">64</property>
<property name="receiveBufferSize">128</property>
<!-- mysql port -->
<property name="port">3306</property>  #设置Amoeba要连接的mysql数据库的端口,默认是3306
<!-- mysql schema -->
<property name="schema">testdb</property>  #设置缺省的数据库,当连接amoeba时,操作表必须显式的指定数据库名,即采用dbname.tablename的方式,不支持 use dbname指定缺省库,因为操作会调度到各个后端dbserver
<!-- mysql user -->
<property name="user">test1</property>  #设置amoeba连接后端数据库服务器的账号和密码,因此需要在所有后端数据库上创建该用户,并授权amoeba服务器可连接
<property name="password">111111</property>
</factoryConfig>
<poolConfig class="com.meidusa.toolkit.common.poolable.PoolableObjectPool">
<property name="maxActive">500</property>  #最大连接数,默认500
<property name="maxIdle">500</property>    #最大空闲连接数
<property name="minIdle">1</property>    #最新空闲连接数
<property name="minEvictableIdleTimeMillis">600000</property>
<property name="timeBetweenEvictionRunsMillis">600000</property>
<property name="testOnBorrow">true</property>
<property name="testOnReturn">true</property>
<property name="testWhileIdle">true</property>
</poolConfig>
</dbServer>
<dbServer name="writedb" parent="abstractServer">  #设置一个后端可写的dbServer,这里定义为writedb,这个名字可以任意命名,后面还会用到
<factoryConfig>
<!-- mysql ip -->
<property name="ipAddress">192.168.2.204</property> #设置后端可写dbserver
</factoryConfig>
</dbServer>
<dbServer name="slave" parent="abstractServer">  #设置后端可读dbserver
<factoryConfig>
<!-- mysql ip -->
<property name="ipAddress">192.168.2.205</property>
</factoryConfig>
</dbServer>
<dbServer name="myslave" virtual="true">  #设置定义一个虚拟的dbserver,实际上相当于一个dbserver组,这里将可读的数据库ip统一放到一个组中,将这个组的名字命名为myslave
<poolConfig class="com.meidusa.amoeba.server.MultipleServerPool">
<!-- Load balancing strategy: 1=ROUNDROBIN , 2=WEIGHTBASED , 3=HA-->
<property name="loadbalance">1</property>  #选择调度算法,1表示复制均衡,2表示权重,3表示HA, 这里选择1
<!-- Separated by commas,such as: server1,server2,server1 -->
<property name="poolNames">slave</property>  #myslave组成员
</poolConfig>
</dbServer>
</amoeba:dbServers>

另一个配置文件amoeba.xml

[root@bogon amoeba]# cat conf/amoeba.xml 
<?xml version="1.0" encoding="gbk"?>

<!DOCTYPE amoeba:configuration SYSTEM "amoeba.dtd">
<amoeba:configuration xmlns:amoeba="http://amoeba.meidusa.com/">

    <proxy>

        <!-- service class must implements com.meidusa.amoeba.service.Service -->
        <service name="Amoeba for Mysql" class="com.meidusa.amoeba.mysql.server.MySQLService">
            <!-- port -->
            <property name="port">8066</property>    #设置amoeba监听的端口,默认是8066

            <!-- bind ipAddress -->    #下面配置监听的接口,如果不设置,默认监听所以的IP
            <!-- 
            <property name="ipAddress">127.0.0.1</property>
             -->

            <property name="connectionFactory">
                <bean class="com.meidusa.amoeba.mysql.net.MysqlClientConnectionFactory">
                    <property name="sendBufferSize">128</property>
                    <property name="receiveBufferSize">64</property>
                </bean>
            </property>

            <property name="authenticateProvider">
                <bean class="com.meidusa.amoeba.mysql.server.MysqlClientAuthenticator">


# 提供客户端连接amoeba时需要使用这里设定的账号 (这里的账号密码和amoeba连接后端数据库服务器的密码无关)

                    <property name="user">root</property>    


                    <property name="password">123456</property>

                    <property name="filter">
                        <bean class="com.meidusa.toolkit.net.authenticate.server.IPAccessController">
                            <property name="ipFile">${amoeba.home}/conf/access_list.conf</property>
                        </bean>
                    </property>
                </bean>
            </property>

        </service>

        <runtime class="com.meidusa.amoeba.mysql.context.MysqlRuntimeContext">

            <!-- proxy server client process thread size -->
            <property name="executeThreadSize">128</property>

            <!-- per connection cache prepared statement size  -->
            <property name="statementCacheSize">500</property>

            <!-- default charset -->
            <property name="serverCharset">utf8</property>

            <!-- query timeout( default: 60 second , TimeUnit:second) -->
            <property name="queryTimeout">60</property>
        </runtime>

    </proxy>

    <!-- 
        Each ConnectionManager will start as thread
        manager responsible for the Connection IO read , Death Detection
    -->
    <connectionManagerList>
        <connectionManager name="defaultManager" class="com.meidusa.toolkit.net.MultiConnectionManagerWrapper">
            <property name="subManagerClassName">com.meidusa.toolkit.net.AuthingableConnectionManager</property>
        </connectionManager>
    </connectionManagerList>

        <!-- default using file loader -->
    <dbServerLoader class="com.meidusa.amoeba.context.DBServerConfigFileLoader">
        <property name="configFile">${amoeba.home}/conf/dbServers.xml</property>
    </dbServerLoader>

    <queryRouter class="com.meidusa.amoeba.mysql.parser.MysqlQueryRouter">
        <property name="ruleLoader">
            <bean class="com.meidusa.amoeba.route.TableRuleFileLoader">
                <property name="ruleFile">${amoeba.home}/conf/rule.xml</property>
                <property name="functionFile">${amoeba.home}/conf/ruleFunctionMap.xml</property>
            </bean>
        </property>
        <property name="sqlFunctionFile">${amoeba.home}/conf/functionMap.xml</property>
        <property name="LRUMapSize">1500</property>
        <property name="defaultPool">writedb</property>  #设置amoeba默认的池,这里设置为writedb


        <property name="writePool">writedb</property>  #这两个选项默认是注销掉的,需要取消注释,这里用来指定前面定义好的俩个读写池
        <property name="readPool">myslave</property>   #

        <property name="needParse">true</property>
    </queryRouter>
</amoeba:configuration>

2.5 在masterdb上创建数据库testdb

mysql> create database testdb;
Query OK, 1 row affected (0.08 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mydb               |
| mysql              |
| performance_schema |
| test               |
| testdb             |
+--------------------+
6 rows in set (0.00 sec)

查看slavedb是否复制成功

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mydb               |
| mysql              |
| performance_schema |
| test               |
| testdb             |
+--------------------+
6 rows in set (0.00 sec)

分别在masterdb和slavedb上为amoedb授权

mysql> GRANT ALL ON testdb.* TO 'test1'@'192.168.2.203' IDENTIFIED BY '111111';
Query OK, 0 rows affected (0.05 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.02 sec)

启动amoeba

[root@bogon amoeba]# /usr/local/amoeba/bin/launcher
Error: JAVA_HOME environment variable is not set.
[root@bogon amoeba]# vim /etc/profile^C
[root@bogon amoeba]# source /etc/profile
[root@bogon amoeba]# /usr/local/amoeba/bin/launcher
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option PermSize=16m; support was removed in 8.0
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=96m; support was removed in 8.0

The stack size specified is too small, Specify at least 228k
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

报错:

Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
从错误文字上看,应该是由于stack size太小,导致JVM启动失败,要如何修改呢?
其实Amoeba已经考虑到这个问题,并将JVM参数配置写在属性文件里。现在,让我们通过该属性文件修改JVM参数。
修改jvm.properties文件JVM_OPTIONS参数。

[root@bogon amoeba]# vim /usr/local/amoeba/jvm.properties 
改成:JVM_OPTIONS="-server -Xms1024m -Xmx1024m -Xss256k -XX:PermSize=16m -XX:MaxPermSize=96m"
原为:JVM_OPTIONS="-server -Xms256m -Xmx1024m -Xss196k -XX:PermSize=16m -XX:MaxPermSize=96m"

再次启动

[root@bogon ~]# /usr/local/amoeba/bin/launcher
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchStandard(Launcher.java:329)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:239)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
    at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:127)
    at org.codehaus.classworlds.Launcher.main(Launcher.java:110)
Caused by: com.meidusa.toolkit.common.bean.util.InitialisationException: default pool required!,defaultPool=writedb invalid
    at com.meidusa.amoeba.route.AbstractQueryRouter.init(AbstractQueryRouter.java:469)
    at com.meidusa.amoeba.context.ProxyRuntimeContext.initAllInitialisableBeans(ProxyRuntimeContext.java:337)
    ... 11 more
 2016-10-24 18:46:37 [INFO] Project Name=Amoeba-MySQL, PID=1577 , System shutdown ....
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option PermSize=16m; support was removed in 8.0
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=96m; support was removed in 8.0
 2016-10-24 18:50:19 [INFO] Project Name=Amoeba-MySQL, PID=1602 , starting...
log4j:WARN log4j config load completed from file:/usr/local/amoeba/conf/log4j.xml
2016-10-24 18:50:21,668 INFO  context.MysqlRuntimeContext - Amoeba for Mysql current versoin=5.1.45-mysql-amoeba-proxy-3.0.4-BETA
log4j:WARN ip access config load completed from file:/usr/local/amoeba/conf/access_list.conf
2016-10-24 18:50:22,852 INFO  net.ServerableConnectionManager - Server listening on 0.0.0.0/0.0.0.0:8066.

查看端口

[root@bogon ~]# netstat -unlpt | grep java
tcp        0      0 :::8066                     :::*                        LISTEN      1602/java    

由此可知Amoeba启动正常

2.6 测试

远程登陆mysql客户端通过指定amoeba配置文件中指定的用户名、密码、和端口以及amoeba服务器ip地址链接mysql数据库

[root@lys2 ~]# mysql -h192.168.2.203 -uroot -p -P8066
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1364055863
Server version: 5.1.45-mysql-amoeba-proxy-3.0.4-BETA Source distribution

Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 

在testdb中创建表test并插入数据

mysql> use testdb;
Database changed
mysql> create table test_table(id int,password varchar(40) not null);
Query OK, 0 rows affected (0.19 sec)

mysql> show tables;
+------------------+
| Tables_in_testdb |
+------------------+
| test_table       |
+------------------+
1 row in set (0.02 sec)

mysql> insert into test_table(id,password) values('1','test1');
Query OK, 1 row affected (0.04 sec)

mysql> select * from test_table;
+------+----------+
| id   | password |
+------+----------+
|    1 | test1    |
+------+----------+
1 row in set (0.02 sec)

分别登陆masterdb和slavedb查看数据

masterdb:

mysql> use testdb;
Database changed
mysql> show tables;
+------------------+
| Tables_in_testdb |
+------------------+
| test_table       |
+------------------+
1 row in set (0.00 sec)

mysql> select * from test_table;
+------+----------+
| id   | password |
+------+----------+
|    1 | test1    |
+------+----------+
1 row in set (0.03 sec)

slavedb:

mysql> use testdb;
Database changed
mysql> show tables;
+------------------+
| Tables_in_testdb |
+------------------+
| test_table       |
+------------------+
1 row in set (0.00 sec)

mysql> select * from test_table;
+------+----------+
| id   | password |
+------+----------+
|    1 | test1    |
+------+----------+
1 row in set (0.00 sec)

停掉masterdb,然后在客户端分别执行插入和查询功能

masterdb:

  [root@bogon ~]# service mysqld stop
  Shutting down MySQL. SUCCESS!

客户端:

mysql> insert into test_table(id,password) values('2','test2');
ERROR 1044 (42000): Amoeba could not connect to MySQL server[192.168.2.204:3306],拒绝连接
mysql> select * from test_table;
+------+----------+
| id   | password |
+------+----------+
|    1 | test1    |
+------+----------+
1 row in set (0.01 sec)

可以看到,关掉masterdb和写入报错,读正常

开启masterdb上的msyql 关闭slave上的mysql

masterdb:

[root@bogon ~]# service mysqld start
Starting MySQL.. SUCCESS! 

slavedb:

[root@localhost ~]# service mysqld stop
Shutting down MySQL. SUCCESS! 

客户端再次尝试

mysql> insert into test_table(id,password) values('2','test2');
Query OK, 1 row affected (0.19 sec)

mysql> select * from test_table;
ERROR 1044 (42000): poolName=myslave, no valid pools

可以看到插入成功,读取失败

开启slavedb上的mysql,查看数据是否自动同步

slavedb:

[root@localhost ~]# service mysqld start
Starting MySQL... SUCCESS! 

客户端:

mysql> select * from test_table;
+------+----------+
| id   | password |
+------+----------+
|    1 | test1    |
|    2 | test2    |
+------+----------+
2 rows in set (0.01 sec)

接着客户端:

mysql> insert into test_table(id,password) values('3','test3');
Query OK, 1 row affected (0.03 sec)

mysql> select * from test_table;
+------+----------+
| id   | password |
+------+----------+
|    1 | test1    |
|    2 | test2    |
|    3 | test3    |
+------+----------+
3 rows in set (0.02 sec)

OK 一切正常,到此全部结束

注:关于mysql主从同步自行查看博主之前的主从同步笔记!

  • Amoeba主配置文件($AMOEBA_HOME/conf/amoeba.xml),用来配置Amoeba服务的基本参数,如Amoeba主机地址、端口、认证方式、用于连接的用户名、密码、线程数、超时时间、其他配置文件的位置等。

  • 数据库服务器配置文件($AMOEBA_HOME/conf/dbServers.xml),用来存储和配置Amoeba所代理的数据库服务器的信息,如:主机IP、端口、用户名、密码等。

  • 切分规则配置文件($AMOEBA_HOME/conf/rule.xml),用来配置切分规则。

  • 数据库函数配置文件($AMOEBA_HOME/conf/functionMap.xml),用来配置数据库函数的处理方法,Amoeba将使用该配置文件中的方法解析数据库函数。

  • 切分规则函数配置文件($AMOEBA_HOME/conf/ruleFunctionMap.xml),用来配置切分规则中使用的用户自定义函数的处理方法。

  • 访问规则配置文件($AMOEBA_HOME/conf/access_list.conf),用来授权或禁止某些服务器IP访问Amoeba。

  • 日志规格配置文件($AMOEBA_HOME/conf/log4j.xml),用来配置Amoeba输出日志的级别和方式。

转载:Amoeba+Mysql实现数据库读写分离