依然如此,只要大家跟著我的步驟一步步來,99.99999%是可以測試成功的
centos6.8已不再維護,可能很多人的虛擬機器中無法使用yum命令下載docker,
但是阿里源還是可以用的 因為他的centos-vault倉庫裡放了之前版本的centos的包
只需要在centos命令列介面下執行一下幾條命令
sed -i "s|enabled=1|enabled=0|g" /etc/yum/pluginconf.d/fastestmirror.conf mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup curl -o /etc/yum.repos.d/CentOS-Base.repo https://www.xmpan.com/Centos-6-Vault-Aliyun.repo yum clean all yum makecache
然後執行如下命令安裝docker
yum install https://get.docker.com/rpm/1.7.1/centos-6/RPMS/x86_64/docker-engine-1.7.1-1.el6.x86_64.rpm
如果提示檢查軟體失敗什麼的,可以試試使用命令 yum remove docker 刪除docker,再執行安裝
安裝完成後可以給docker配置一下阿里雲的加速器,具體方法自行百度,在此不再過多贅述
docker安裝完成後開始準備搭建Mysql,我一直強調開發中應秉承約定>配置>編碼,接下來就按部就班先準備環境:
我準備了兩臺虛擬機器130(主),和131(從),首先在兩臺電腦上分別通過docker安裝mysql
因為需要配置讀寫分離,一定要掛載mysql配置檔案目錄到主機
docker pull mysql:5.6 //拉取mysql映象 docker run -p 3306:3306 --name mysql -v $PWD/conf:/etc/mysql/conf.d -v $PWD/logs:/logs -v $PWD/data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=123456 -d mysql:5.6 docker cp containedID:/etc/mysql/my.cnf $PWD //拷貝一份容器內的配置檔案
兩臺虛擬機器執行相同的操作,配置主從Mysql的資料庫版本最好一致
首先是主庫的my.cnf的配置:
在mysql的配置檔案的 [mysqld] 下面修改(從庫也是如此):
#開啟主從複製,主庫的配置(log-bin屬性在配置主從時才指定,單機不需要) log-bin= mysql3306-bin #指定主庫serverid #server-id 主庫和從庫都需要指定,不過主庫的server-id必須小於從庫的server-id(重要) server-id=1 #指定同步的資料庫,如果不指定則同步全部資料庫(一般不需要指定) #binlog-do-db=mybatis_1128 #(配置檔案中輸入的這些命令一定要和下面有一行空格,不然MySQL不識別)
執行SQL語句查詢狀態:
SHOW MASTER STATUS
需要記錄下Position值,需要在從庫中設定同步起始值。(重要)
然後重啟130(主),使配置檔案生效
docker restart containerID
配置131(從)的my.cnf:
僅僅需要指定一個server-id=2即可
然後重啟131(從),使配置檔案生效
通過sqlyog連線兩臺mysql伺服器(注意開放埠,筆者為了測試,直接停掉了防火牆)
接著在130(主)中輸入以下命令:
GRANT REPLICATION SLAVE ON *.* TO 'slave01'@'192.168.209.131'IDENTIFIED BY '123456'; FLUSH PRIVILEGES;
意思是新增一個slave可以登入的使用者,使用者名稱為slave01,密碼為123456,只有通過131(從),才可登入
完成後在131(從)中執行以下命令:
CHANGE MASTER TO MASTER_HOST='192.168.209.130', MASTER_USER='slave01', MASTER_PASSWORD='123456', MASTER_PORT=3306, MASTER_LOG_FILE='mysql3306-bin.000011', MASTER_LOG_POS=38301; START SLAVE;//開啟主從配置 SHOW SLAVE STATUS //檢視主從配置狀態資訊
38301以及mysql3308-bin.000011對應130(主)中的position和file欄位(重要)
如果 show slave status 後,slave_io_running 和slave_sql_running 值都為yes,則配置成功,
直接在130(主)上隨便建個資料庫,發現131(從)也生成了相同的資料庫
到此,Mysql主從配置結束。
很多人配置完成後,就開始在程式碼中配置雙資料來源,通過程式碼來實現資料來源的切換以達到讀寫分離的目的,我一直強調,約定>配置>編碼,這種做法顯然是不可取的,既然配置了主從,為什麼不去選擇一種高效明瞭的管理方式呢?
這就引出了這篇文章的重點:mycat
mycat是
1、一個徹底開源的,面向企業應用開發的大資料庫叢集
2、支援事務、ACID、可以替代MySQL的加強版資料庫
3、一個可以視為MySQL叢集的企業級資料庫,用來替代昂貴的Oracle叢集
4、一個融合記憶體快取技術、NoSQL技術、HDFS大資料的新型SQL Server
5、結合傳統資料庫和新型分散式資料倉儲的新一代企業級資料庫產品
6、一個新穎的資料庫中介軟體產品
mycat就是為叢集而生的,並能通過簡單配置達到資料庫分片的目的
- 下載安裝Mycat 執行如下命令:
docker pull longhronshens/mycat-docker mkdir -p /usr/local/mycat cd /usr/local/mycat
進入我們新建的mycat目錄,將server.xml rule.xml schema.xml複製到該目錄下,三個檔案的基本內容如下:schema.xml
<?xml version="1.0"?> <!DOCTYPE mycat:schema SYSTEM "schema.dtd"> <mycat:schema xmlns:mycat="http://io.mycat/"> <schema name="TESTDB" checkSQLschema="false" sqlMaxLimit="100"> <!-- auto sharding by id (long) --> <table name="travelrecord" dataNode="dn1,dn2,dn3" rule="auto-sharding-long" /> <!-- global table is auto cloned to all defined data nodes ,so can join with any table whose sharding node is in the same data node --> <table name="company" primaryKey="ID" type="global" dataNode="dn1,dn2,dn3" /> <table name="goods" primaryKey="ID" type="global" dataNode="dn1,dn2" /> <!-- random sharding using mod sharind rule --> <table name="hotnews" primaryKey="ID" autoIncrement="true" dataNode="dn1,dn2,dn3" rule="mod-long" /> <!-- <table name="dual" primaryKey="ID" dataNode="dnx,dnoracle2" type="global" needAddLimit="false"/> <table name="worker" primaryKey="ID" dataNode="jdbc_dn1,jdbc_dn2,jdbc_dn3" rule="mod-long" /> --> <table name="employee" primaryKey="ID" dataNode="dn1,dn2" rule="sharding-by-intfile" /> <table name="customer" primaryKey="ID" dataNode="dn1,dn2" rule="sharding-by-intfile"> <childTable name="orders" primaryKey="ID" joinKey="customer_id" parentKey="id"> <childTable name="order_items" joinKey="order_id" parentKey="id" /> </childTable> <childTable name="customer_addr" primaryKey="ID" joinKey="customer_id" parentKey="id" /> </table> <!-- <table name="oc_call" primaryKey="ID" dataNode="dn1$0-743" rule="latest-month-calldate" /> --> </schema> <!-- <dataNode name="dn1$0-743" dataHost="localhost1" database="db$0-743" /> --> <dataNode name="dn1" dataHost="localhost1" database="db1" /> <dataNode name="dn2" dataHost="localhost1" database="db2" /> <dataNode name="dn3" dataHost="localhost1" database="db3" /> <!--<dataNode name="dn4" dataHost="sequoiadb1" database="SAMPLE" /> <dataNode name="jdbc_dn1" dataHost="jdbchost" database="db1" /> <dataNode name="jdbc_dn2" dataHost="jdbchost" database="db2" /> <dataNode name="jdbc_dn3" dataHost="jdbchost" database="db3" /> --> <dataHost name="localhost1" maxCon="1000" minCon="10" balance="0" writeType="0" dbType="mysql" dbDriver="native" switchType="1" slaveThreshold="100"> <heartbeat>select user()</heartbeat> <!-- can have multi write hosts --> <writeHost host="hostM1" url="192.168.209.130:3306" user="root" password="123456"> <!-- can have multi read hosts --> <readHost host="hostS2" url="192.168.209.130:3306" user="root" password="123456" /> </writeHost> <writeHost host="hostS1" url="192.168.209.130:3306" user="root" password="123456" /> <!-- <writeHost host="hostM2" url="localhost:3316" user="root" password="123456"/> --> </dataHost> <!-- <dataHost name="sequoiadb1" maxCon="1000" minCon="1" balance="0" dbType="sequoiadb" dbDriver="jdbc"> <heartbeat> </heartbeat> <writeHost host="hostM1" url="sequoiadb://1426587161.dbaas.sequoialab.net:11920/SAMPLE" user="jifeng" password="jifeng"></writeHost> </dataHost> <dataHost name="oracle1" maxCon="1000" minCon="1" balance="0" writeType="0" dbType="oracle" dbDriver="jdbc"> <heartbeat>select 1 from dual</heartbeat> <connectionInitSql>alter session set nls_date_format='yyyy-mm-dd hh24:mi:ss'</connectionInitSql> <writeHost host="hostM1" url="jdbc:oracle:thin:@127.0.0.1:1521:nange" user="base" password="123456" > </writeHost> </dataHost> <dataHost name="jdbchost" maxCon="1000" minCon="1" balance="0" writeType="0" dbType="mongodb" dbDriver="jdbc"> <heartbeat>select user()</heartbeat> <writeHost host="hostM" url="mongodb://192.168.0.99/test" user="admin" password="123456" ></writeHost> </dataHost> <dataHost name="sparksql" maxCon="1000" minCon="1" balance="0" dbType="spark" dbDriver="jdbc"> <heartbeat> </heartbeat> <writeHost host="hostM1" url="jdbc:hive2://feng01:10000" user="jifeng" password="jifeng"></writeHost> </dataHost> --> <!-- <dataHost name="jdbchost" maxCon="1000" minCon="10" balance="0" dbType="mysql" dbDriver="jdbc"> <heartbeat>select user()</heartbeat> <writeHost host="hostM1" url="jdbc:mysql://localhost:3306" user="root" password="123456"> </writeHost> </dataHost> --> </mycat:schema>
server.xml
<?xml version="1.0" encoding="UTF-8"?> <!-- - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. --> <!DOCTYPE mycat:server SYSTEM "server.dtd"> <mycat:server xmlns:mycat="http://io.mycat/"> <system> <property name="useSqlStat">0</property> <!-- 1為開啟實時統計、0為關閉 --> <property name="useGlobleTableCheck">0</property> <!-- 1為開啟全加班一致性檢測、0為關閉 --> <property name="sequnceHandlerType">2</property> <!-- <property name="useCompression">1</property>--> <!--1為開啟mysql壓縮協議--> <!-- <property name="fakeMySQLVersion">5.6.20</property>--> <!--設定模擬的MySQL版本號--> <!-- <property name="processorBufferChunk">40960</property> --> <!-- <property name="processors">1</property> <property name="processorExecutor">32</property> --> <!--預設為type 0: DirectByteBufferPool | type 1 ByteBufferArena--> <property name="processorBufferPoolType">0</property> <!--預設是65535 64K 用於sql解析時最大文字長度 --> <!--<property name="maxStringLiteralLength">65535</property>--> <!--<property name="sequnceHandlerType">0</property>--> <!--<property name="backSocketNoDelay">1</property>--> <!--<property name="frontSocketNoDelay">1</property>--> <!--<property name="processorExecutor">16</property>--> <!-- <property name="serverPort">8066</property> <property name="managerPort">9066</property> <property name="idleTimeout">300000</property> <property name="bindIp">0.0.0.0</property> <property name="frontWriteQueueSize">4096</property> <property name="processors">32</property> --> <!--分散式事務開關,0為不過濾分散式事務,1為過濾分散式事務(如果分散式事務內只涉及全域性表,則不過濾),2為不過濾分散式事務,但是記錄分散式事務日誌--> <property name="handleDistributedTransactions">0</property> <!-- off heap for merge/order/group/limit 1開啟 0關閉 --> <property name="useOffHeapForMerge">1</property> <!-- 單位為m --> <property name="memoryPageSize">1m</property> <!-- 單位為k --> <property name="spillsFileBufferSize">1k</property> <property name="useStreamOutput">0</property> <!-- 單位為m --> <property name="systemReserveMemorySize">384m</property> <!--是否採用zookeeper協調切換 --> <property name="useZKSwitch">true</property> </system> <!-- 全域性SQL防火牆設定 --> <!-- <firewall> <whitehost> <host host="127.0.0.1" user="mycat"/> <host host="127.0.0.2" user="mycat"/> </whitehost> <blacklist check="false"> </blacklist> </firewall> --> <user name="root"> <property name="password">123456</property> <property name="schemas">TESTDB</property> <!-- 表級 DML 許可權設定 --> <!-- <privileges check="false"> <schema name="TESTDB" dml="0110" > <table name="tb01" dml="0000"></table> <table name="tb02" dml="1111"></table> </schema> </privileges> --> </user> <user name="user"> <property name="password">user</property> <property name="schemas">TESTDB</property> <property name="readOnly">true</property> </user> </mycat:server>
rule.xml
<?xml version="1.0" encoding="UTF-8"?> <!-- - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. --> <!DOCTYPE mycat:rule SYSTEM "rule.dtd"> <mycat:rule xmlns:mycat="http://io.mycat/"> <tableRule name="rule1"> <rule> <columns>id</columns> <algorithm>func1</algorithm> </rule> </tableRule> <tableRule name="rule2"> <rule> <columns>user_id</columns> <algorithm>func1</algorithm> </rule> </tableRule> <tableRule name="sharding-by-intfile"> <rule> <columns>sharding_id</columns> <algorithm>hash-int</algorithm> </rule> </tableRule> <tableRule name="auto-sharding-long"> <rule> <columns>id</columns> <algorithm>rang-long</algorithm> </rule> </tableRule> <tableRule name="mod-long"> <rule> <columns>id</columns> <algorithm>mod-long</algorithm> </rule> </tableRule> <tableRule name="sharding-by-murmur"> <rule> <columns>id</columns> <algorithm>murmur</algorithm> </rule> </tableRule> <tableRule name="crc32slot"> <rule> <columns>id</columns> <algorithm>crc32slot</algorithm> </rule> </tableRule> <tableRule name="sharding-by-month"> <rule> <columns>create_time</columns> <algorithm>partbymonth</algorithm> </rule> </tableRule> <tableRule name="latest-month-calldate"> <rule> <columns>calldate</columns> <algorithm>latestMonth</algorithm> </rule> </tableRule> <tableRule name="auto-sharding-rang-mod"> <rule> <columns>id</columns> <algorithm>rang-mod</algorithm> </rule> </tableRule> <tableRule name="jch"> <rule> <columns>id</columns> <algorithm>jump-consistent-hash</algorithm> </rule> </tableRule> <function name="murmur" class="io.mycat.route.function.PartitionByMurmurHash"> <property name="seed">0</property><!-- 預設是0 --> <property name="count">2</property><!-- 要分片的資料庫節點數量,必須指定,否則沒法分片 --> <property name="virtualBucketTimes">160</property><!-- 一個實際的資料庫節點被對映為這麼多虛擬節點,預設是160倍,也就是虛擬節點數是物理節點數的160倍 --> <!-- <property name="weightMapFile">weightMapFile</property> 節點的權重,沒有指定權重的節點預設是1。以properties檔案的格式填寫,以從0開始到count-1的整數值也就是節點索引為key,以節點權重值為值。所有權重值必須是正整數,否則以1代替 --> <!-- <property name="bucketMapPath">/etc/mycat/bucketMapPath</property> 用於測試時觀察各物理節點與虛擬節點的分佈情況,如果指定了這個屬性,會把虛擬節點的murmur hash值與物理節點的對映按行輸出到這個檔案,沒有預設值,如果不指定,就不會輸出任何東西 --> </function> <function name="crc32slot" class="io.mycat.route.function.PartitionByCRC32PreSlot"> <property name="count">2</property><!-- 要分片的資料庫節點數量,必須指定,否則沒法分片 --> </function> <function name="hash-int" class="io.mycat.route.function.PartitionByFileMap"> <property name="mapFile">partition-hash-int.txt</property> </function> <function name="rang-long" class="io.mycat.route.function.AutoPartitionByLong"> <property name="mapFile">autopartition-long.txt</property> </function> <function name="mod-long" class="io.mycat.route.function.PartitionByMod"> <!-- how many data nodes --> <property name="count">3</property> </function> <function name="func1" class="io.mycat.route.function.PartitionByLong"> <property name="partitionCount">8</property> <property name="partitionLength">128</property> </function> <function name="latestMonth" class="io.mycat.route.function.LatestMonthPartion"> <property name="splitOneDay">24</property> </function> <function name="partbymonth" class="io.mycat.route.function.PartitionByMonth"> <property name="dateFormat">yyyy-MM-dd</property> <property name="sBeginDate">2015-01-01</property> </function> <function name="rang-mod" class="io.mycat.route.function.PartitionByRangeMod"> <property name="mapFile">partition-range-mod.txt</property> </function> <function name="jump-consistent-hash" class="io.mycat.route.function.PartitionByJumpConsistentHash"> <property name="totalBuckets">3</property> </function> </mycat:rule>
啟動mycat
docker run --name mycat -v /usr/local/mycat/schema.xml:/usr/local/mycat/conf/schema.xml -v /usr/local/mycat/rule.xml:/usr/local/mycat/conf/rule.xml -v /usr/local/mycat/server.xml:/usr/local/mycat/conf/server.xml --privileged=true -p 8066:8066 -p 9066:9066 -e MYSQL_ROOT_PASSWORD=123456 -d longhronshens/mycat-docker
- 配置mycat mycat正常啟動後就可以開始配置mycat關於Mysql的叢集配置了 首先是schema.xml中的配置:
<schema name="TESTDB" checkSQLschema="false" sqlMaxLimit="100">//一個schema標籤就是一個邏輯庫,是我們連線mycat所要查詢的庫,對應於Mysql物理庫中的database name:庫名稱 checkSQLschema:mycat對sql語句的過濾策略 <table name="company" dataNode="dn1,dn2,dn3" rule="crc32slot" type="global" /> //一個table就是一個邏輯表,表名稱為company,dataNode為庫節點,需要配置分片就寫多個,用逗號隔開,沒有分片就寫一個,rule為分片策略,對應於rule.xml中的策略 </schema>//type="global"為全域性策略,親自測試配置上這個屬性後,資料將會重複插入所有的db1,db2,db3中,分片不起作用
<dataNode name="dn1" dataHost="localhost1" database="db1" /> //database對應物理資料庫 name對應上邊schema節點的dataNode屬性
<dataNode name="dn2" dataHost="localhost1" database="db2" />
<dataNode name="dn3" dataHost="localhost1" database="db3" /><dataHost name="localhost1" maxCon="1000" minCon="10" balance="1"
writeType="0" dbType="mysql" dbDriver="native" switchType="1" slaveThreshold="100"> //writeType屬性負載均衡型別,目前的取值有3種:
1. writeType="0", 所有寫操作傳送到配置的第一個writeHost,第一個掛了切到還生存的第二個writeHost,重新啟動後已切換後的為準,切換記錄在配置檔案中:dnindex.properties .
2. writeType="1",所有寫操作都隨機的傳送到配置的writeHost。
3. writeType="2",沒實現。1.當balance=0 時,不開啟讀寫分離,所有讀操作都發生在當前的writeHost上
當balance=1 ,所有讀操作都隨機傳送到當前的writeHost對應的readHost和備用的writeHost 一般配置讀寫分離balance值為1即可
當balance=2,所有的讀操作都隨機傳送到所有的writeHost,readHost上
當balance=3 ,所有的讀操作都只傳送到writeHost的readHost上
<heartbeat>select user()</heartbeat>
<!-- can have multi write hosts -->
<writeHost host="hostM1" url="192.168.209.130:3306" user="root"
password="123456"> //130(主) 寫操作
<readHost host="hostS1" url="192.168.209.131:3306" user="root" password="123456" /> //131(從) 讀操作
<!-- can have multi read hosts -->
</writeHost>
<!-- <writeHost host="hostM2" url="localhost:3316" user="root" password="123456"/> -->
</dataHost>然後是server.xml的配置
<user name="root"> <property name="password">123456</property> //mycat對外提供服務的使用者名稱和密碼,使用Mycat後,就直接將mycat當成mysql使用即可 <property name="schemas">TESTDB</property> //邏輯庫名稱對應schema.xml中的名字 <!-- 表級 DML 許可權設定 --> <!-- <privileges check="false"> <schema name="TESTDB" dml="0110" > <table name="tb01" dml="0000"></table> <table name="tb02" dml="1111"></table> </schema> </privileges> --> </user>
rule.xml
<function name="crc32slot" class="io.mycat.route.function.PartitionByCRC32PreSlot"> <property name="count">3</property><!-- 要分片的資料庫節點數量,必須指定,否則沒法分片 --> </function>
- 配置130(主),131(從)資料庫 在130(主)上新建db1,db2,db3三個資料庫(mycat只能新建表,無法新建資料庫,表也必須是schema.xml中指定過的table)
- 測試mycat 我的mycat與130(主)是同一臺虛擬機器,在130(主)上重新啟動Mycat,使配置檔案生效(schema.xml 中 去掉type="global"屬性)
mycat對外提供服務的預設埠號為8066
在mycat中建立表:CREATE TABLE `company` ( `id` BIGINT(20) NOT NULL AUTO_INCREMENT, `username` VARCHAR(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '使用者名稱', `password` VARCHAR(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '密碼,加密儲存', `phone` VARCHAR(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '註冊手機號', `email` VARCHAR(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '註冊郵箱', `created` DATETIME(0) NOT NULL, `updated` DATETIME(0) NOT NULL, PRIMARY KEY (`id`) );
在Mycat中插入資料:
INSERT INTO company(id,username) VALUES('1','張飛'); INSERT INTO company(id,username) VALUES('2','樊噲'); INSERT INTO company(id,username) VALUES('3','曹操'); INSERT INTO company(id,username) VALUES('4','劉備'); INSERT INTO company(id,username) VALUES('5','龐統'); INSERT INTO company(id,username) VALUES('6','許諸'); INSERT INTO company(id,username) VALUES('7','趙雲'); INSERT INTO company(id,username) VALUES('8','關羽'); INSERT INTO company(id,username) VALUES('9','關羽1'); INSERT INTO company(id,username) VALUES('10','關羽2'); INSERT INTO company(id,username) VALUES('11','關羽3'); INSERT INTO company(id,username) VALUES('12','關羽4'); INSERT INTO company(id,username) VALUES('13','關羽5');
然後檢視130(主)資料庫資料:
db1:
db2:
mycat中執行查詢 select * from company:
資料都能查出來,沒有問題
接下來在131(從)db1插入一條資料,這時130(主)中沒有該條資料,繼續在mycat中執行查詢select * from company;
查出來了該test資料,說明讀寫分離配置成功。